toRef和toRefs
可以把一个不是ref的对象变成ref
看不懂就直接看例子吧
//此处没用toRef
<template>
<h1>姓名:{{ obj.name }}</h1>
<h1>年龄:{{ obj.age }}</h1>
<h1>薪资:{{ obj.obj2.xz }}</h1>
<button @click="obj.name += '.'">修改名字</button>
<button @click="obj.age += 1">修改年龄</button>
<button @click="obj.obj2.xz += 1000">加钱</button>
</template>
<script>
import { reactive } from "vue";
export default {
name: "WatchDemo",
setup() {
let obj = reactive({
name: "小孙",
age: 18,
obj2: {
xz: 2000,
},
});
return {
obj,
};
},
};
</script>
<style>
</style>
//此处用了toRef
<template>
<h1>姓名:{{ name }}</h1>
<h1>年龄:{{ age }}</h1>
<h1>薪资:{{ xz }}</h1>
<button @click="name += '.'">修改名字</button>
<button @click="age += 1">修改年龄</button>
<button @click="xz += 1000">加钱</button>
</template>
<script>
import { reactive, toRef } from "vue";
export default {
name: "WatchDemo",
setup() {
let obj = reactive({
name: "小孙",
age: 18,
obj2: {
xz: 2000,
},
});
return {
name: toRef(obj, "name"),
age: toRef(obj, "age"),
xz: toRef(obj.obj2, "xz"),
};
},
};
</script>
<style>
</style>
看明白了吗?用了toRef,你可以简化在模板中对数据的使用(千万不可以不用toRef直接在setup中使用简化,不会生效的,因为不用的话,你只是吧初始值赋给你retun的数据,不会有响应式)
toRefs就是可以直接简化,一个对象,例如
<template>
<h1>姓名:{{ name }}</h1>
<h1>年龄:{{ age }}</h1>
<h1>薪资:{{ obj2.xz }}</h1>
<button @click="name += '.'">修改名字</button>
<button @click="age += 1">修改年龄</button>
<button @click="obj2.xz += 1000">加钱</button>
</template>
<script>
import { reactive, toRefs } from "vue";
export default {
name: "WatchDemo",
setup() {
let obj = reactive({
name: "小孙",
age: 18,
obj2: {
xz: 2000,
},
});
return {
...toRefs(obj)
};
},
};
</script>
<style>
</style>