由于reactive必须传递一个对象,所以在实际开发中如果只是想让某个变量实现响应式的时候回非常麻烦,所以Vue3提供了ref方法实现简单值的监听。
对此有两句话不理解:
1.ref是否可以对对象进行监听呢?
2.如何体现出reactive对某个变量实现响应式的时候很麻烦呢?是否可进行举例说明?
下面这个示例,不能体现问题2是吗?
<script>
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({ count: 0 })
function increment() {
state.count++
}
// 不要忘记同时暴露 increment 函数
return {
state,
increment
}
}
}
</script>
<template>
<button @click="increment">
{{ state.count }}
</button>
</template>
关于问题 2
你想你要用
reactive
存一个值,但是reactive
只能接受对象吧?所以要用一个对象把值包起来:reactive({ value: 0 })
,这个是不是和ref
有点像?然后麻烦在哪?
ref
那么安全,或者说严谨。你写了const counter = reactive({ value: 0 })
,别人写一个counter.val = 0
,也是可以运行的,容易造成混乱。当然这个可以用 TypeScript 解决const counter: { value: number } = reactive({ value: 0 })
,这也会增加麻烦;反之你写const counter = ref(0)
就肯定不会有人在counter
后面乱写别的东西ref
在模板中自动解包的便利。假如counter
是个ref
你就可以这么写<MyComp :value="counter" />
、<button @click="counter ++">+1</button>