vue3中toRef、toRefs和toRaw的使用

1.toRef

 toRef 的作用是将一个响应式对象中的属性转换成单独的响应式引用。转换后的响应式引用会跟踪原始属性的变化。转换后的响应式可以被用于计算属性监听器中。

如果原始对象是非响应式的则不会更新视图,数据会改变。

接收两个参数:

  • 参数一:原始对象;
  • 参数二:属性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div>
    {{ man }}
  </div>
  <br><div>
    <button>点击</button>
  </div>
 
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)
}

点击前页面:

点击后结果:

2.toRefs

 toRefs 将一个对象的所有属性变成响应式引用,追踪原对象的引用关系。

原始对象如果是响应式的,则当修改属性值时,数据和视图都会更新;原对象如果非响应式,则修改属性值时,数据会更新,视图不更新。

接收一个参数:原始对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div>
    {{ man }}
  </div>
  <br><div>
    <button>点击2</button>
  </div>
 
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
}

 点击前页面:

点击后结果:

3.toRaw

 toRaw 将一个响应式对象变成非响应式。修改属性值时,数据会改变,视图不会更新。

接受一个参数:原始对象。 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div>
    {{ man }}
  </div>
  <br><div>
    <button>点击3</button>
  </div>
 
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))
}

 点击前与点击后页面:

点击后结果:

到此这篇关于vue3中toRef、toRefs和toRaw的使用的文章就介绍到这了,更多相关vue3 toRef toRefs toRaw内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部! 

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/js/11034.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部