1.创建文件
stores
-index.js
-global.js
2.对应文件内容 index.js
安装插件 npm i pinia-plugin-persistedstate
import { createPinia } from 'pinia';
import persist from 'pinia-plugin-persistedstate';
const pinia = createPinia();
pinia.use(persist);
export default pinia;
3.对应文件内容 global.js
import { defineStore } from 'pinia';
import { ref,reactive } from "vue";
export const useGlobalStore = defineStore('global', () => {
const tabBarStatus = ref('1');
const system = ref({})
const changeTabBarStatus = (status) => {
tabBarStatus.value = status; // 示例:改变 tabBarStatus 的值
};
const setSystem=(options)=>{
system.value=options;
}
const getSystem=()=>{
return system.value;
}
return {
tabBarStatus,
system,
changeTabBarStatus,
setSystem,
getSystem
};
},
{
// 网页端配置
// persisit:true,
// 小程序端 修改其设置 获取方法
persist:{
storage:{
getItem(key){
return uni.getStorageSync(key);
},
setItem(key,value){
uni.setStorageSync(key,value);
}
}
}
});
4.注册到main.js中
import App from './App'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import pinia from '@/stores/index'
export function createApp() {
const app = createSSRApp(App)
app.use(pinia);
return {
app
}
}
// #endif
如果想在utils 下的工具中使用可以使用一下写法
import pinia from '@/stores/index.js'
import { useGlobalStore } from "@/stores/global";
const globalStore = useGlobalStore(pinia)
export default {
getUploadImageDomainName(){
return globalStore.system.img_host;
}
}