vue使用watch监听pinia状态值的改变

1,056 阅读1分钟

定义store

/store/app.ts

import { defineStore } from 'pinia'
export const useAppStore = defineStore('app', {
  state: () =>{
    return {
      title: '',
    }
  },
  getters: {
    getTitle(){
      return this.title
    }
  }
})

父组件内监听

/views/app/app.vue

<script setup>
import { storeToRefs } from 'pinia'
import { watch } from 'vue'
import { useAppStore } from '@/store/app'

const appStore = useAppStore()
watch(
  ()=> appStore.getTitle,
  (newVlue)=>{
    console.log('appStore.title.watch>>>',newVlue);
  },
  {deep: true}
)
</script>

子组件修改值

/views/components/children.vue

import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'

const { title } = storeToRefs(useAppStore())
title.value = '子组件修改值'