- ref:Ref 可以持有任何类型的值,包括深层嵌套的对象、数组或者 JavaScript 内置的数据结构
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<!-- 在模板中使用 ref 时,我们不需要附加 .value -->
<button @click="increment">
{{ count }}
</button>
</template>
- reactive:另一种响应式状态,它有一定的局限性,后面会列举
<script setup>
import { reactive } from 'vue'
const state = reactive({ count: 0 })
</script>
<template>
<button @click="state.count++">
{{ state.count }}
</button>
</template>
- reactive的局限性
1、有限的值类型:只适用于对象类型,像string,number,boolean不行
2、对解构操作不友好:解构出来的值已经不具备响应式的能力,所以谨慎
3、不能替换整个对象:整个对象替换也会失去响应式的能力,所以只能改变对象的某个或多个值