缘由
片段
ref
<script setup>
import { ref, triggerRef, watchEffect } from 'vue'
const text = 'Hello World!'
const msg = ref(text)
watchEffect(() => {
console.log(msg.value)
})
function change() {
msg.value = text
triggerRef(msg) // whatever the msg.value is change or not the watchEffect's callback will called
}
</script>
<template>
<h1>{{ msg }}</h1>
<button @click="change">
Click
</button>
</template>
computed
当然,不仅是ref声明的变量可以,computed也可以,毕竟computed返回一个只读的响应式 ref 对象。该 ref 通过 .value 暴露 getter 函数的返回值。
<script setup>
import { ref, triggerRef, watchEffect, computed } from 'vue'
const text = 'Hello World!'
const msg = ref(text)
const cMsg = computed(() => {
return msg.value
})
watchEffect(() => {
console.log(cMsg.value)
})
function change() {
msg.value = text
triggerRef(msg) // whatever the msg.value is change or not the watchEffect's callback will called
}
</script>
<template>
<h1>{{ msg }}</h1>
<button @click="change">
Click
</button>
</template>