安装:
npm i pinia
在main.ts中引入
import { createApp } from 'vue';
//挂载在app上
createApp(App).use(router).use(createPinia()).mount('#app');
新建store文件夹,新建index.ts
import { defineStore } from 'pinia';
export const userStore = defineStore('storeId', {
state: () => {
return {
num: 17,
age: '48',
name: '苦哈哈',
};
},
getters: {
changeNum() {
return this.num + 10;
},
},
// 同步和异步都可以写
actions: {
upNum(val) {
this.num += val;
},
},
});
在文件中使用
pinia
getters:{{ changeNum }}
{{ num }}
{{ name }}
{{ age }}
pinia可以根据名称直接划分模块,不需要借助modules
新建user.ts,shop.ts
import { defineStore } from 'pinia';
export const user = defineStore('user', {
state: () => {
return {
username: 'Admin',
};
},
getters: {
changeNum() {
return this.username + '今天是周三';
},
},
actions: {
changeUsername(val){
this.username = val
}
},
});
import { defineStore } from 'pinia';
export const shop = defineStore('shop', {
state: () => {
return {
goods: ['鞋子', '珠宝', '包包'],
akf: '0000000',
};
},
getters: {
changeGoods() {},
},
actions: {
changeCoodsname() {},
},
});
在文件中使用
pinia模块{{ username }}
getters:{{ changeNum }}
GOODS-----{{ akf }}
{{ goods }}
npm i pinia-plugin-persistedstate -S
在main.ts中引用
import piniaStore from './store';
createApp(App).use(router).use(piniaStore).mount('#app');
index.ts
import { createPinia } from 'pinia';
import { useAppStore } from './modules/app';
import { useUserStore } from './modules/user';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
export { useAppStore, useUserStore };
export default pinia;
app.ts
import { createPinia } from 'pinia';
import { useAppStore } from './modules/app';
import { useUserStore } from './modules/user';
//引入持久化
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
//使用插件
export { useAppStore, useUserStore };
export default pinia;
在模块中开启缓存
import { defineStore } from 'pinia';
import piniaStore from '/@/store/index';
export const useAppStore = defineStore(
// 唯一ID
'app',
{
state: () => ({
title: 'FastVue3,一个快速开箱即用的Vue3+Vite模板',
}),
getters: {},
actions: { },
//配置缓存
persist: {
key: 'theme',
//存储在localstorage还是sessionStorage中
storage: localStorage,
//哪个数据需要持久化
paths: ['theme'],
},
},
);