先看例子吧。
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
<template>
<Demo/>
template>
<script>
import Demo from './components/Demo.vue'
export default {
name: 'App',
components: {
Demo
}
}
script>
<template>
<h2>姓名:{{person.name}}h2>
<h2>年龄:{{person.age}}h2>
<h2>薪酬:{{person.job.salary}}Kh2>
<button @click="person.name+='~'">修改姓名button>
<button @click="person.age++">增长年龄button>
<button @click="person.job.salary++">涨薪button>
template>
<script>
import {reactive} from "vue";
export default {
name:"Demo",
setup(){
let person = reactive({
name:"张三",
age:18,
job:{
salary:30
}
})
return {
person
}
}
}
script>
好,现在我们来仔细看下Demo.vue,template
标签里{{person.name}}
、{{person.age}}
、{{person.job.salary}}
、person.name+='~'
、person.age++
、person.job.salary++
,person person的,哪儿哪儿都是person。能不能不重复写person,就像下图右侧那样。
先尝试下吧,比如这样修改Demo.vue,如下。
<template>
<h2>姓名:{{name}}h2>
<h2>年龄:{{age}}h2>
<h2>薪酬:{{salary}}Kh2>
<button @click="name+='~'">修改姓名button>
<button @click="age++">增长年龄button>
<button @click="salary++">涨薪button>
template>
<script>
import {reactive} from "vue";
export default {
name:"Demo",
setup(){
let person = reactive({
name:"张三",
age:18,
job:{
salary:30
}
})
return {
name:person.name,
age:person.age,
salary:person.job.salary
}
}
}
script>
这时,toRef
的给力就凸显出来了。瞧哈!
<template>
<h2>姓名:{{name}}h2>
<h2>年龄:{{age}}h2>
<h2>薪酬:{{salary}}Kh2>
<button @click="name+='~'">修改姓名button>
<button @click="age++">增长年龄button>
<button @click="salary++">涨薪button>
template>
<script>
import {reactive, toRef} from "vue";
export default {
name:"Demo",
setup(){
let person = reactive({
name:"张三",
age:18,
job:{
salary:30
}
})
return {
name:toRef(person,"name"),
age:toRef(person,"age"),
salary:toRef(person.job,"salary")
}
}
}
script>
toRef
,将一个数据变成响应式数据。
toRefs
,将多个数据变成响应式数据。
<template>
<h2>姓名:{{name}}h2>
<h2>年龄:{{age}}h2>
<h2>薪酬:{{job.salary}}Kh2>
<button @click="name+='~'">修改姓名button>
<button @click="age++">增长年龄button>
<button @click="job.salary++">涨薪button>
template>
<script>
import {reactive,toRefs} from "vue";
export default {
name:"Demo",
setup(){
let person = reactive({
name:"张三",
age:18,
job:{
salary:30
}
})
console.log("toRef(person)=",toRefs(person));
return {
...toRefs(person)
}
}
}
script>