美文网首页
pinia 的用法(替代vuex)

pinia 的用法(替代vuex)

作者: 莫问前程F6 | 来源:发表于2021-12-10 12:50 被阅读0次

安装

npm i pinia@next
npm i @vueuse/core

引入pinia

import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core'

interface ThemeConfig {
    mainColor: String, 
}

const _themeConfigImpl: ThemeConfig = { 
    mainColor: 'red'
 };
  
const useTheme = defineStore({
    // id: 必须的,在所有 Store 中唯一
    id: "useTheme",
    // state: 返回对象的函数
    state: ()=> ({
 
        // 所保存的对象
        config: useStorage('themeConfig', _themeConfigImpl),      
        
    }),

    getters: {

    }, 

    actions: {
        changeTheme(config: ThemeConfig){
                this.config.mainColor = config.mainColor;
        }
    }
})
export {
    useTheme,   ThemeConfig
}

调用

import {ThemeConfig, useTheme} from '@/api/comm/useTheme';
const themeStore = useTheme();
const myConfig: ThemeConfig = { 
    mainColor: 'blue'
};

 let _toggleColor = ()=> {
    myConfig.mainColor = themeStore.config.mainColor == 'blue' ? 'red': 'blue';
    themeStore.changeTheme(myConfig)
 };

相关文章

网友评论

      本文标题:pinia 的用法(替代vuex)

      本文链接:https://www.haomeiwen.com/subject/fmecfrtx.html