1.ref、reactive的区别
reactive
- 定义复杂类型响应式数据;
- proxy类型,内部基于ES6的 proxy 实现;
ref
- 定义一个响应式数据,普通类型和复杂类型都可;
- 最外层:响应式依然是靠Object.defineProperty()的get与set完成的
- 对象类型的数据:内部基于 proxy 实现;
2.注意事项
ref、reactive变量可以监听到数据的变化,用时需注意不可直接替换变量。
//父组件
<template>
<div style="color: #fff; font-size: 25px">
<div>parent: {{ temp }}</div>
<div class="button" @click="updateObj">1. 点我全量更换数据</div>
<div class="button" @click="updateAttr">2. 点我添加属性</div>
<div class="button" @click="updateData">3. 点我修改数据</div>
<Child :temp="temp"></Child>
</div>
</template>
<script>
import Child from "./child.vue";
import { ref, reactive } from "vue";
export default {
name: "",
components: { Child },
setup() {
let temp = reactive({ a: 1 }); // Proxy {a: 1}
console.log("------create---temp: ", temp);
function updateObj() {
temp = { a: 1, b: 2 }; //此时reactiveData已变为普通变量,非reactive变量
console.log("------updateObj---temp: ", temp); //{a: 1, b: 2}
}
function updateAttr() {
temp.b = 10;
}
function updateData() {
temp.a = 10;
}
return { temp, updateObj, updateAttr, updateData };
},
};
</script>
<style lang="less" scoped>
.button {
width: 200px;
text-align: center;
padding: 10px 5px;
margin: 30px 0px;
border: solid 1px #fff;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
</style>
//子组件
<template>
<div>
child: {{temp}}
</div>
</template>
<script>
export default {
name: "",
props: {
temp: {
type: Object,
required: true
}
},
}
</script>
- 上面例子中,如果点击1,再点击2、3,页面数据无变化
- 直接点击2、3可看到数据变化,原因是点1触发的函数直接修改了变量的指向