缘由

有时在开发过程中,如果值未更新也想要触发副作用

片段

ref

  1. <script setup>
  2. import { ref, triggerRef, watchEffect } from 'vue'
  3. const text = 'Hello World!'
  4. const msg = ref(text)
  5. watchEffect(() => {
  6. console.log(msg.value)
  7. })
  8. function change() {
  9. msg.value = text
  10. triggerRef(msg) // whatever the msg.value is change or not the watchEffect's callback will called
  11. }
  12. </script>
  13. <template>
  14. <h1>{{ msg }}</h1>
  15. <button @click="change">
  16. Click
  17. </button>
  18. </template>

computed

当然,不仅是ref声明的变量可以,computed也可以,毕竟computed返回一个只读的响应式 ref 对象。该 ref 通过 .value 暴露 getter 函数的返回值。

  1. <script setup>
  2. import { ref, triggerRef, watchEffect, computed } from 'vue'
  3. const text = 'Hello World!'
  4. const msg = ref(text)
  5. const cMsg = computed(() => {
  6. return msg.value
  7. })
  8. watchEffect(() => {
  9. console.log(cMsg.value)
  10. })
  11. function change() {
  12. msg.value = text
  13. triggerRef(msg) // whatever the msg.value is change or not the watchEffect's callback will called
  14. }
  15. </script>
  16. <template>
  17. <h1>{{ msg }}</h1>
  18. <button @click="change">
  19. Click
  20. </button>
  21. </template>