ai问答:Vue3中使用computed和watch监听pinia数据的区别

发布时间 2023-06-09 10:14:35作者: 让梦想纵横

在Vue3中,通过computed来监听pinia中的state数据:

import { defineStore } from 'pinia'
import { useStore } from 'pinia'
import { computed } from 'vue'

const store = defineStore('store', {/* ... */})

export default {
  setup() {
    const doubledCount = computed(() => {
      return useStore().count * 2
    })
    
    return {
      doubledCount
    }
  }
}

这里,通过computed()创建一个计算属性doubledCount,在getter函数中使用useStore()获取pinia的state,并返回计算后的值。
那么doubledCount就会依赖store.count,当store.count变化时,doubledCount也会更新。

watch

import { defineStore } from 'pinia'
import { useStore } from 'pinia'
import { watch } from 'vue'

const store = defineStore('store', {/* ... */})

export default {
  setup() {
    const localCount = useStore().count
    
    watch(localCount, (newValue) => {
      // 监听localCount,当store.count变化时也会触发
      console.log(newValue)
    })
  }
}

这里,通过useStore()从pinia state中获取localCount。
然后通过watch来监听localCount,因为localCount依赖store.count,所以当store.count变化时,watch的回调也会触发,实现了pinia state变化的响应。