美文网首页
vue3 学习笔记 - ref

vue3 学习笔记 - ref

作者: VioletJack | 来源:发表于2023-03-29 10:10 被阅读0次

ref

ref 函数接受一个内部值,返回一个响应式的,可更改的 ref 对象。此对象只有一个指向内布置的熟悉 .value。ref 函数可以接受基础类型和引用类型的值。如果将一个对象赋值给 ref,那么这个对象将通过 reactive 函数转成深层次响应式的对象。

使用 ref 需要进行引用

import { ref, reactive } from 'vue'

数字

const r1 = ref(1)
r1.value++
// 2

字符串

const r2 = ref('hello')
r2.value += ' world'
// hello world
const rt0 = reactive(r2)
rt0.value += ' bibi'
// hello world bibi
const rt00 = reactive({ r2 })
rt00.r2 += ' cici'
// hello world bibi cici

布尔

const r3 = ref(false)
r3.value = true
r3.value = 'oh li gei'
// value 是不限定类型的
// oh li gei

数组

const r4 = ref([])
r4.value.push(111)
r4.value.push(222)
r4.value.push(333)
// [ 111, 222, 333 ]
const rt4 = reactive(r4)
rt4.value.push(444)
// [ 111, 222, 333, 444 ]
const rt44 = reactive({ r4 })
rt44.r4.push(555)
// [ 111, 222, 333, 444, 555 ]

Set

const r5 = ref(new Set())
r5.value.add('777')
r5.value.add('888')
const rt = reactive(r5)
// { "Set(2)": [ "777", "888" ] }
rt.value.add('999')
// 无法解构

对象

const r6 = ref({ a: 2, b: { c: [] } })
r6.value.b.c.push('546')
// { "a": 2, "b": { "c": [ "546" ] } }
const rt2 = reactive(r6)
rt2.value.a = 4
// 无法解构
const rt22 = reactive({ r6 })
rt22.r6.a = 9
// 可以解构

特别注意的是,ref 函数返回的对象无法直接使用 reactive 函数进行解构(即去掉 .value),需要包裹在一个对象 {} 中。

相关文章

网友评论

      本文标题:vue3 学习笔记 - ref

      本文链接:https://www.haomeiwen.com/subject/emrxddtx.html