1. 安装pinia
npm i pinia
yarn add pinia
2.创建Store文件
import { createPinia } from 'pinia';
const store = createPinia();
export default store;
3.在main.js 入口文件中集成store
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
createApp(App).use(router).use(store).mount('#app');
4.在store文件夹下面可以创建多个片段仓库(模块化)
import { defineStore } from 'pinia';
export const user = defineStore('user', {
state: () => {
return {
name: '朱小明',
age: 24,
};
},
getters: {
sum(){
return 2*6
}
},
actions: {
changeAge(val) {
this.age += val;
},
},
});
5.在组件中使用状态数据或者方法
import { storeToRefs } from 'pinia';
import { user } from '../store/user';
const userStore = user();
const { name, age, sum } = storeToRefs(userStore);
const add = () => {
userStore.age += 2;
};
const add2 = () => {
userStore.$patch({
name: '蘑菇头',
});
};
const add3 = () => {
userStore.$patch((state) => {
state.age++;
state.name = state.name === '朱小明' ? '蘑菇头' : '朱小明';
});
};
const add4 = () => {
};
actions: {
changeAge(val) {
this.age += val;
},
},
const onadd = () => {
userStore.changeAge(5)
}
首先需要在store 片段中定义好函数比如
getters: {
sum(){
return 2*6
}
},
const { name, age, sum } = storeToRefs(userStore);
6.pinia的持久化存储
npm i pinia-plugin-persistedstate
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const store = createPinia();
store.use(piniaPluginPersistedstate);
export default store;
import { defineStore } from 'pinia';
export const homeStore = defineStore('home', {
state: () => {
return {
title: '待办事件',
v_show: false,
lists: [
{
checkbox: false,
text_content: '找工作',
id: 1,
},
{
checkbox: false,
text_content: '学习知识',
id: 2,
},
{
checkbox: false,
text_content: '爱你一万年',
id: 3,
},
],
};
},
getters: {},
actions: {},
persist: true,
});