首先创建一个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)
});

Logo

前往低代码交流专区

更多推荐