Vue3.0中的reactive
reactive
是 Vue3 中提供的实现响应式数据的方法。- 在 Vue2 中响应式数据是通过 defineProperty 来实现的,
- 在 Vue3 中响应式数据是通过 ES6 的
Proxy
来实现的。 - reactive 参数必须是对象 (json / arr)
- 如果给 reactive 传递了其它对象
- 默认情况下,修改对象无法实现界面的数据绑定更新。
- 如果需要更新,需要进行重新赋值。(即不允许直接操作数据,需要放个新的数据来替代原数据)
#### 在 reactive
使用基本类型参数
基本类型(数字、字符串、布尔值)在 reactive
中无法被创建成 proxy
对象,也就无法实现监听。
<template>
<div>
<p>{
{msg}}</p>
<button @click="c">button</button>
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
name: 'App',
setup() {
let msg = reactive(0)
function c() {
console.log(msg);
msg ++;
}
return {
msg,
c
};
}
}
</script>
点击 button ,我们期望的结果是数字从 0 变成 1,然而实际上界面上的数字并没有发生任何改变。
查看控制台,它的输出是这样的(我点了 3 次)
出现提示
value cannot be made reactive: 0
而输出的值确实发生了变化,只不过这种变化并没有反馈到界面上,也就是说并没有实现双向数据绑定。当然,如果是 re