一:Vue 3.0
1:toRef
将一个对象的属性变为响应式的对象。
原始写法:
<template>
<h2>姓名: {{ person.name }}</h2>
<h2>年龄: {{ person.age }}</h2>
<h2>薪资: {{ person.job.j1.salary }}</h2>
<button @click="person.name+='~'">修改姓名</button>
<button @click="person.age++">修改年龄</button>
<button @click="person.job.j1.salary++">涨薪</button>
</template>
<script>
import {reactive} from 'vue';
export default {
name: "Demo",
setup() {
let person = reactive({
name: '张三',
age: 18,
job: {
j1: {
salary: 20
}
}
})
return {
person,
}
}
}
</script>
toRef写法
<template>
<h2>姓名: {{ name }}</h2>
<h2>年龄: {{ age }}</h2>
<h2>薪资: {{ salary }}</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">修改年龄</button>
<button @click="salary++">涨薪</button>
</template>
<script>
import {reactive, toRef, toRefs} from 'vue';
export default {
name: "Demo",
setup() {
let person = reactive({
name: '张三',
age: 18,
job: {
j1: {
salary: 20
}
}
})
return {
name: toRef(person, "name"),
age: toRef(person, "age"),
salary: toRef(person.job.j1, "salary"),
}
}
}
</script>
roRefs写法:
toRefs只能解构一层。
<template>
<h2>姓名: {{ name }}</h2>
<h2>年龄: {{ age }}</h2>
<h2>薪资: {{ job.j1.salary }}</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">修改年龄</button>
<button @click="job.j1.salary++">涨薪</button>
</template>
<script>
import {reactive, toRef, toRefs} from 'vue';
export default {
name: "Demo",
setup() {
let person = reactive({
name: '张三',
age: 18,
job: {
j1: {
salary: 20
}
}
})
return {
...toRefs(person)
}
}
}
</script>