基础实例
先看例子吧。
- main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
- App.vue
<template>
<Demo/>
</template>
<script>
import Demo from './components/Demo.vue'
export default {
name: 'App',
components: {
Demo
}
}
</script>
- Demo.vue
<template>
<h2>姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}}</h2>
<h2>薪酬:{{person.job.salary}}K</h2>
<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}}K</h2>
<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>
来测试下效果:name、age和salary失去了响应式。
正确修改:使用toRef
这时,toRef
的给力就凸显出来了。瞧哈!
<template>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪酬:{{salary}}K</h2>
<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
的功能类似ref
,让数据保持响应式。
正确修改:使用toRefs
toRef
,将一个数据变成响应式数据。
toRefs
,将多个数据变成响应式数据。
<template>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪酬:{{job.salary}}K</h2>
<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>