Vue3$Data-RefAndReactive

80 阅读2分钟

Vue3$Data-RefAndReactive

数据的改变引起页面的变化。Vue 是通过使数据变成代理来实现的,Vue3 中具体而言就是 refreactive函数。 由于reactive有一些限制,官方推荐使用ref

1. ref()

0. Basic Usage

ref可以定义任何类型的数据。

  • <script>中使用时,需要使用.value来获取
  • <template>中使用时,顶级属性和单独的值可以省略(解包)
<script setup>
import { ref } from 'vue'

const count = ref(0)
function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">
    {{ count }}
  </button>
</template>

1. Ref Unwrapping 解包

0. 模板中自动解包({{}} / @event中)
1. 在模板中解包的注意事项
	1. 只有顶级的ref属性会解包
	2. 最终计算值会解包({{}}) final evaluated value of a text interpolation
2. 作为reactive的属性
	1. 对象的属性:自动解包
	2. 数组和集合的元素array and collection:不解包
	- not shallow reactive object

2. reactive()

0. Basic Usage

Reactive Objects are JavaScript Proxies.
为保证访问代理的一致性,对同一个原始对象调用reactive()会总是返回同样的代理对象,而对一个已存在的代理对象调用 reactive() 会返回其本.
	这个规则对嵌套对象也适用。依靠深层响应性,响应式对象内的嵌套对象依然是代理:
<script setup>
import { reactive } from 'vue'

const state = reactive({ count: 0 })
</script>

<template>
<button @click="state.count++">
  {{ state.count }}
</button>
</template>
const proxy = reactive({})

const raw = {}
proxy.nested = raw

console.log(proxy.nested === raw) // false

1. Limitations of reactive()

0. 只能object对象类型
1. 不能替换整个对象:替换后失去了响应式。
2. 对解构操作不友好:当我们将响应式对象的原始类型属性解构为本地变量时 / 将该属性传递给函数时,我们将丢失响应性连接。
const state = reactive({ count: 0 })

// 当解构时,count 已经与 state.count 断开连接
let { count } = state
// 不会影响原始的 state
count++

// 该函数接收到的是一个普通的数字
// 并且无法追踪 state.count 的变化
// 我们必须传入整个对象以保持响应性
callSomeFunction(state.count)

Links

VueReactivityFundamentals