1.toref
toref 的作用是将一个响应式对象中的属性
转换成单独的响应式引用。转换后的响应式引用会跟踪原始属性
的变化。转换后的响应式可以被用于计算属性
及监听器
中。
如果原始对象是非响应式的则不会更新视图,数据会改变。
接收两个参数:
- 参数一:原始对象;
- 参数二:属性。
<template> <div> {{ man }} </div> <br /> <div> <button @click="change">点击</button> </div> </template> <script setup lang="ts"> import { toref, torefs, reactive, toraw } from 'vue' const man = reactive({ name: '张三', age: 18, like: '唱' }) const like = toref(man, 'like') const change = () => { man.age = 19 like.value = '跳' console.log(man) } </script>
点击前页面:
点击后结果:
2.torefs
torefs 将一个对象的所有属性变成响应式引用,追踪原对象的引用关系。
原始对象如果是响应式的,则当修改属性值时,数据和视图都会更新;原对象如果非响应式,则修改属性值时,数据会更新,视图不更新。
接收一个参数:原始对象。
<template> <div> {{ man }} </div> <br /> <div> <button @click="change2">点击2</button> </div> </template> <script setup lang="ts"> import { toref, torefs, reactive, toraw } from 'vue' const man = reactive({ name: '张三', age: 18, like: '唱' }) const { name, age } = torefs(man) const change2 = () => { name.value = '李四' age.value = 20 } </script> <style scoped></style>
点击前页面:
点击后结果:
3.toraw
toraw 将一个响应式对象变成非响应式。修改属性值时,数据会改变,视图不会更新。
接受一个参数:原始对象。
<template> <div> {{ man }} </div> <br /> <div> <button @click="change3">点击3</button> </div> </template> <script setup lang="ts"> import { toref, torefs, reactive, toraw } from 'vue' const man = reactive({ name: '张三', age: 18, like: '唱' }) const change3 = () => { // 手写toraw console.log(man['__v_raw']) // 调用toraw console.log(toraw(man)) } </script>
点击前与点击后页面:
点击后结果:
到此这篇关于vue3中toref、torefs和toraw的使用的文章就介绍到这了,更多相关vue3 toref torefs toraw内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论