toRef和toRefs
作用:创建一个ref对象,其value指向另一个对象中得某一个属性
语法:const name = toRef(data,‘name’)
应用:要将响应式对象中得某个属性单独提供给外部使用时
拓展:toRefs与toRef功能一致 但可以批量创建多个ref对象 语法:toref(data)
为了能在template写的简短,引用toRef处理
被toRef包裹的响应式,修改时候直接读取原来响应式reactive代理属性 实时响应变化
不使用toRef则响应式的修改就会出现Bug
// 使用toRef进行对某个重新赋值的属性添加响应式
const skill = toRef(data,‘skill’)
const age = toRef(data,‘age’)
const name = toRef(data,‘name’)
const salary = toRef(data,‘salary’)
console.log(skill,‘哈哈哈’)
return {data,skill,age,salary,name}
toRefs为了完善toRef
1.toRefs可以直接处理多个属性的解构
2.可以简化代码
const allProps = toRefs(data)
// return {data,skill,age,salary,name}
return {data,...allProps} //对上面return进行简化代码
打印allProps结果:
age: ObjectRefImpl {_object: Proxy, _key: 'age', __v_isRef: true}
name: ObjectRefImpl {_object: Proxy, _key: 'name', __v_isRef: true}
position: ObjectRefImpl {_object: Proxy, _key: 'position', __v_isRef: true}
salary: ObjectRefImpl {_object: Proxy, _key: 'salary', __v_isRef: true}
skill: ObjectRefImpl {_object: Proxy, _key: 'skill', __v_isRef: true}
使用完整示例如下:
template
<template>
<h1>toRef</h1>
<div>
<p>姓名1:{{data.name}}</p>
<p>姓名2:{{name}}</p>
<p>年龄1:{{data.age}}</p>
<p>年龄2:{{age}}</p>
<p>薪资1:{{data.salary}}</p>
<p>薪资2:{{salary}}</p>
<p>岗位1:{{data.position}}</p>
<p>岗位2:{{data.position}}</p>
<ul>
掌握技能1:
<li v-for="(item,index) in data.skill" :key="index">
{{item.type}} {{item.level}}
</li>
</ul>
<ul>
掌握技能2:
<li v-for="(item,index) in skill" :key="index+100">
{{item.type}} {{item.level}}
</li>
</ul>
</div>
<button @click="data.age++">增加工龄</button>
<button @click="data.salary+= 100">涨薪</button>
</template>
js
<script>
import {reactive,watch,toRef,toRefs} from 'vue'
export default {
name: 'DemoVueApp',
setup(){
const data = reactive({
name:'张三',
age:27,
salary:20000,
position:'高级软件开发',
skill:[
{
type:'javascript',
level:'精通'
},
{
type:'typescript',
level:'熟练'
},
{
type:'react',
level:'精通'
},
{
type:'vue',
level:'精通'
},
{
type:'anglar',
level:'熟悉'
},
{
type:'java',
level:'了解'
}
]
})
watch(()=>data.age,(newVal)=>{
if(newVal>27){
data.salary = (newVal-27)*2000+20000
}
})
// 使用toRef
const skill = toRef(data,'skill')
const age = toRef(data,'age')
const name = toRef(data,'name')
const salary = toRef(data,'salary')
console.log(skill,'哈哈哈')
// 使用toRefs
const allProps = toRefs(data)
/*
打印allProps结果:
age: ObjectRefImpl {_object: Proxy, _key: 'age', __v_isRef: true}
name: ObjectRefImpl {_object: Proxy, _key: 'name', __v_isRef: true}
position: ObjectRefImpl {_object: Proxy, _key: 'position', __v_isRef: true}
salary: ObjectRefImpl {_object: Proxy, _key: 'salary', __v_isRef: true}
skill: ObjectRefImpl {_object: Proxy, _key: 'skill', __v_isRef: true}
*/
// return {data,skill,age,salary,name}
return {data,...allProps} //对上面return进行简化代码
}
};
</script>