Vue3 提供了两种方式构建响应式数据:ref 和 reactive
ref 用于构建简单值的响应式数据,基于 Object.defineProperty 监听 value 值
reactive 用于构建复杂的响应式数据,基于 Proxy 对数据进行深度监听
基本用法
<template>
<div>
<!-- ref -->
<p>支持人数:{{ supNum }}</p>
<p>反对人数:{{ oppNum }}</p>
<p>支持率:{{ ratio }}</p>
<button @click="changeNum(0)">支持</button>
<button @click="changeNum(1)">反对</button>
<!-- reactive -->
<p>支持人数:{{ stateSupNum }}</p>
<p>反对人数:{{ stateOppNum }}</p>
<p>支持率:{{ stateRatio }}</p>
<button @click="changeStateNum(0)">支持</button>
<button @click="changeStateNum(1)">反对</button>
</div>
</template>
<script>
import {
ref,
reactive,
toRefs,
computed,
} from 'vue'
export default {
// 初始化 props 和 beforeCreate 之间
setup() {
// 构建响应式数据 ref - 一般处理简单值的响应式,基于 Object.defineProperty 监听 value 值
let supNum = ref(0)
let oppNum = ref(0)
const changeNum = (type) => {
type === 0 ? supNum.value++ : oppNum.value++
}
// 计算属性
let ratio = computed(() => {
let total = supNum.value + oppNum.value
return total === 0
? '--'
: ((supNum.value / total) * 100).toFixed(2) + '%'
})
// 构建响应式数据 reactive - 基于 Proxy 对数据进行深度监听,以此构建响应式
let state = reactive({
stateSupNum: 0,
stateOppNum: 0,
})
const changeStateNum = (type) => {
type === 0 ? state.stateSupNum++ : state.stateOppNum++
}
// 把 reactive 中的每一项变成 ref 响应式数据
// console.log(toRefs(state))
// 计算属性
let stateRatio = computed(() => {
let total = state.stateSupNum + state.stateOppNum
return total === 0
? '--'
: ((state.stateSupNum / total) * 100).toFixed(2) + '%'
})
return {
supNum,
oppNum,
changeNum,
ratio,
...toRefs(state),
changeStateNum,
stateRatio,
}
},
}
</script>