toRefs与toRef区别:
相同点:
- 将结构解析出来的值具有响应式
- 修改数据是会影响到原始数据,所以它是引用值
- 都是通过:原本是proxy({ name: 'aa' }) toRefs 转换后变成{name:proxy(value:'aa')}
不同点:
- toRefs接受一个参数,即一个需要响应的obj,如果接收定义的key没有则响应会失败
- toRef 接受两个参数,第一个是响应的obj,第二个需要响应的key,如果自定义的key 没有则可以默认是空,继续进行响应,如果找到相应的key则根据相应的Key相应数据
toRefs 例子如下: 解决将对象或者数组等 解构出来的变量失去 响应:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
Vue.createApp({
setup(props, context) {
const {
reactive,
toRefs
} = Vue
let content = reactive({
name: 'aa'
})
const {
name
} = toRefs(content)
setTimeout(() => {
content.name = 'bb'
}, 2000)
return {
name
}
},
template: '<div>{{name}}</div>'
}).mount('#root')
</script>
</html>
toRefs如果定义的name2没有则会失去响应,控制台报错例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
Vue.createApp({
setup(props, context) {
const {
reactive,
toRefs
} = Vue
let content = reactive({
name: 'aa'
})
let {
name2
} = toRefs(content)
setTimeout(() => {
name2.value = 'bb'
}, 2000)
return {
name2
}
},
template: '<div>{{name2}}</div>'
}).mount('#root')
</script>
</html>
使用toRef解决解构数据中无响应key问题如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
Vue.createApp({
setup(props, context) {
const {
reactive,
toRef
} = Vue
let content = reactive({
name: 'aa'
})
let name2 = toRef(content, 'name2')
setTimeout(() => {
name2.value = 'bb'
}, 2000)
return {
name2
}
},
template: '<div>{{name2}}</div>'
}).mount('#root')
</script>
</html>