vue3使用pinia实现全局变量共享,主动监听变化,并与localStorage的值同步

首先创建一个js文件

// themeStyle.js
import {defineStore} from 'pinia';

export const useThemeStyleStore = defineStore('themeStyle', {
    state: () => ({
        backgroundColor1: localStorage.getItem('backgroundColor1') || '#000000',
    }),
    actions: {
        setBackgroundColor1(backgroundColor1) {
            this.backgroundColor1 = backgroundColor1;
            localStorage.setItem('backgroundColor1', backgroundColor1);
        },
    },
});


/**
 *  引入方式
 *  import {useThemeStyleStore} from "@/views/drawing/store/themeStyle";
 *  const myThemeStyleStore = useThemeStyleStore();
 */

然后创建一个公共文件,方便直接引入

//themeStore.js
import {useThemeStyleStore} from “@/store/station/themeStyle”;

export const themeStyleStore = useThemeStyleStore();


然后在要赋值的页面引入

//one.vue
<el-button style="background-color: #000000" @click="handleTheme('#000000')"></el-button>
    <el-button style="background-color: #212830" @click="handleTheme('#212830')"></el-button>

<script setup>
import {themeStyleStore} from "@/store/station/themeStore";

//在方法中赋值
function handleTheme(val) {
  themeStyleStore.setBackgroundColor1(val)
}
</script>

然后在另一个页面主动监听值的变化

//two.vue
import {themeStyleStore} from "@/store/station/themeStore";

watch(() => themeStyleStore.backgroundColor1, (newValue, oldValue) => {
  console.log(newValue)
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值