ref and reactive are the APIs used to implement data responsiveness in Vue3
Generally, ref
Define basic data types, reactive
Define reference data types
reactive defines reference data types (taking objects and arrays as examples), which can combine complex The internal attributes or data items of the data type are declared as responsive data, so the responsiveness of reactive is deep, and the bottom layer is to implement data responsiveness through ES6's Proxy
, relatively Based on Vue2's Object.defineProperty
, it has the advantages of being able to monitor additions and deletions, as well as changes in object properties.
Examples of using reactive to define object data types
const paginationConfig = reactive({ pageNum: 1, pageSize: 10 }) // 定义 const onChange = () => { paginationConfig.pageNum = 2 // js使用 paginationConfig.pageSize = 20 // js使用 }
<!-- Vue3模板引用使用 --> <a-pagination v-model:current="paginationConfig.pageNum"></a-pagination>
If using reactive Define the basic data type, Vue3 will report a warning error, as shown in the figure
const str = reactive('我是字符串')
.value suffix when using it in a script. However, it is not required in the template. This is because Vue3 will automatically add it for you, which makes ref more convenient than reactive. Simple
let num = ref(0) // 定义 let isShow = ref(false) // 定义 const onChange = () => { num.value++ // js使用 isShow.value = true // js使用 }
<!-- Vue3模板引用使用 --> <a-modal v-model:visible="isShow"></a-modal>
const tableData = ref([]) // 定义 const getTableData = async () => { const { data } = await getTableDataApi() // 模拟接口获取表格数据 tableData.value = data // 修改 }
<!-- Vue3模板引用使用 --> <a-table v-model:dataSource="tableData"></a-table>
const tableData = reactive([]) // 定义 const getTableData = async () => { const { data } = await getTableDataApi() // 模拟接口获取表格数据 tableData = data // 修改,错误示例,这样赋值会使tableData失去响应式 }
<!-- Vue3模板引用使用 --> <a-table v-model:dataSource="tableData"></a-table>
// 方法一:改为 ref 定义 const tableData = ref([]) const getTableData = async () => { const { data } = await getTableDataApi() tableData.value = data // 使用.value重新赋值 } // 方法二:使用 push 方法 const tableData = reactive([]) const getTableData = async () => { const { data } = await getTableDataApi() tableData.push(...data) // 先使用...将data解构,再使用push方法 } // 方法三:定义时数组外层嵌套一个对象 const tableData = reactive({ list:[] }) const getTableData = async () => { const { data } = await getTableDataApi() tableData.list = data // 通过访问list属性重新赋值 } // 方法四:赋值前再包一层 reactive const tableData = reactive([]) const getTableData = async () => { const { data } = await getTableDataApi() tableData = reactive(data) // 赋值前再包一层reactive }
The above is the detailed content of How to use ref and reactive in Vue3. For more information, please follow other related articles on the PHP Chinese website!