ref 與 reactive 是 vue3 提供給我們用于創建響應式數據的兩個方法。
reactive 常用于創建引用數據,例如:object、array 等。
reactive 則是通過 proxy 來實現的響應式數據,并配合 reflect 操作的源對象。
?reactive 創建引用數據:
<template><p>姓名:{{ info.name }}</p><p>年齡:{{ info.age }}</p><p>性別:{{ info.sex }}</p><button @click="editInfo">修改信息</button>
</template><script>
// 引入 reactive 函數
import { reactive } from 'vue'
export default {name: "Home",setup() {// 使用 reactive 創建引用數據const info = reactive({name: "張三",age: 20,sex: "男"});// 創建方法const editInfo = () => {info.name = "李四";info.age = 22;info.sex = "女";// reactive 創建的數據是一個 proxy 對象,不需要通過 value 獲取console.log(info);}// 返回數據return {info,editInfo}}
}
</script>
reactive 只能創建引用數據(數組或對象)。另外通過 reactive 創建的數據可以直接使用,不需要通過 value 屬性獲取。?
注:reactive 創建的是一個深層次的數據對象,不論多少層,reactive 都能檢測到數據的變化
?reactive 創建數組 :
<template><p v-for="item in userList" :key="item">{{ item }}</p><button @click="editUser">修改人員</button>
</template><script>
// 引入 reactive 函數
import { reactive } from 'vue'
export default {name: "Home",setup() {// 使用 reactive 創建數組const userList = reactive(["張三", "李四", "王五"]);// 創建方法const editUser = () => {// vue3 通過下標修改數據時,頁面也會實時更新userList[0] = "張三豐";console.log(userList);}// 返回數據return {userList,editUser}}
}
</script>
? 注:vue3 通過下標修改數據時,頁面也會實時更新。
原創作者:吳小糖
創作時間:2023.11.23?