1. pinia安装
yarn add pinia
or
npm i pinia
2. 在main.ts中挂载pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')
3. 新建pinia模块
创建store/index.ts模块
export default defineStore('index', {
state: () => {
return ({
tableData: [] as ITableData[],
cartList: [] as IChildren[]
})
},
getters: {},
actions: {
// 添加大类
addBigClass(name: string) {
this.tableData.push({
id: new Date().getTime(),
name,
children: []
});
},
}
})
若有多个模块
- 新建文件store/user.ts
import { defineStore } from "pinia";
export default defineStore("user", {
state() {
return {
userList: [] as IUser[],
};
},
getters: {},
actions: {}
})
2.新建 store/index.ts 文件
import useUserStore from "./user";
export default function useStore() {
return {
user: useUserStore(),
};
}
4. 在组件中使用
<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import useStore from '@/store';
const store = useStore();
const { cartList } = storeToRefs(store); // 将store中的数据解构出来,为任何响应式属性创建 refs
// 访问cartList 通过cartList.value
const className = ref('');
const handleSureClass = () => {
if (className.value.length) {
store.addBigClass(className.value); // 调用pinia中actions中的方法
isShowClass.value = false;
}
}
</script>
pinia数据持久化
- 安装
yarn add pinia-plugin-persistedstate
or
npm i pinia-plugin-persistedstate
- 使用插件 在main.ts中注册
import { createApp } from "vue";
import App from "./App.vue";
import persist from 'pinia-plugin-persistedstate'
const pinia = createPinia();
pinia.use(persist);
createApp(App).use(pinia).mount('#app');
- 模块开启持久化
export default defineStore('index', {
persist: true, // 开启持久化插件
// ...省略
});