Vue3组件不发生变化,如何监听pinia中数据变化?

一、背景前提

在开发过程中,我们需要将一些跨组件使用的的数据在pinia中进行状态管理,组件在初始化的时候我们能通过onMounted,computed,watch,watchEffect获取到存储在pinia state中的内容,有一些特殊情况,在组件初始化之后我们无法通过以上四种情况获取state中的内容,这时候我们怎么做呢?
这时候我们就需要用到$subscribe

二、案例说明

项目中时常我们会设置主题,初始化的时候我们会默认一种主题,在网上我们也可以进行主题切换设置不同的主题。
项目在定制主题时,我们需要主题去配置不同的色系,背景图片等。

接下来,说一下在项目中遇见的问题,及解决方式。

在切换主题的时候,发现在组件中设置的svg背景图片无法通过监听获取state中的主题,在pinia官网中我们找到了答案pinia官网插件

Vue3中我们可以通过v-bind在style中动态绑定样式
使用pinia中$subscribe进行订阅监听

<i class="iClassTop"></i>
<style lang="scss" scoped>
 .iClassTop:hover {
    
     background-image: v-bind(bgurl);}
</style>
import {
    
     useMapStore } from '@/store/index.js'
const mapStore = useMapStore();
const bgurl = ref('');
//这里有坑,mutation的events事件打包后不存在,在获取pinia中值时,需要使用state
mapStore.$subscribe((mutation, state) => {
    
    
bgurl.value = bgurl.value = state.currentSkin==='dark'?'url(\'../light-dark.svg\')':'url(\'../light-white.svg\')';
});

猜你喜欢

转载自blog.csdn.net/weixin_58195668/article/details/129275407