Pinia 的用法
说明书
它没有mutation ,只有state 、getters、actions,快速上手,比vuex用法要简单。
一个 Store (如
Pinia)是一个实体,它持有未绑定到您的组件树的状态和业务逻辑。换句话说,它托管全局状态。它有点像一个始终存在并且每个人都可以读取和写入的组件。它有三个概念,state、getters
和 actions 并且可以安全地假设这些概念等同于组件中的“数据”、“计算”和“方法”。
第一步下载
yarn add pinia
# 或者使用 npm
npm install pinia
第二步 引用 vue3 main.ts 的用法
import { createPinia } from 'pinia'
app.use(createPinia())
第三步 开始写代码
这是store里面的shopcart.ts
import { defineStore } from 'pinia';
import { IGoods } from '@/api/user'
export const useShopcart = defineStore({
id: 'shopcart',
persist: true ,
state(){
let list: IGoods[] = [];
return {
list
}
},
getters:{
getTotal():any{
return this.list.reduce((total: number,goods: IGoods)=>{
return total + goods.count;
},0)
}
},
actions:{
addShopcart(goods: IGoods){
let index =this.list.findIndex((g: IGoods)=>{
return g.id === goods.id
})
if(index !== -1){
this.list[index].count++
}else{
this.list.push({
...goods,
count: 1
});
}
},
subsctractShopcart(goods: IGoods){
let index = this.list.findIndex((g: IGoods) => {
return g.id === goods.id
});
if (this.list[index].count === 1 || this.list[index].count === 0) {
this.delShopcart(index);
}
},
delShopcart(index:number){
this.list.splice(index, 1);
}
}
})
user.ts
//需要定义list的类型
export interface IGoods {
id: number,
title: string,
price: number,
count: number,
img: string
}
组件引用store里面的list数据
<script lang="ts" setup>
import { useShopcart } from '@/store/shopcart' //引入对应的store
import { storeToRefs } from 'pinia'
const shopcartStore = useShopcart();
const add = (goods: IGoods)=>{
goods.count++;
shopcartStore.addShopcart(goods) //调用对应的store 的方法即可
}
const { list } = storeToRefs(shopcartStore) //拿到list数据
//拿到getter的数据
const calc = (index:number)=>{
if (index === 2) return shopcartStore.getTotal;
return '';
}
Pinia 数据持久化储存插件 pinia-plugin-persistedstate
pnpm:
pnpm i pinia-plugin-persistedstate
npm:
npm i pinia-plugin-persistedstate
yarn:
yarn add pinia-plugin-persistedstate
main.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
store 里面的写法
export const useShopcart = defineStore({
id: 'shopcart',
persist: true , // 加上这一行即可
state(){
let list: IGoods[] = [];
return {
list
}
},
})
默认存在localStorage 里面
如果想存在sessionStorage
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(createPersistedState({
storage: sessionStorage,
}))
还可以指定哪个数据存入哪个缓存里面。
import { defineStore } from 'pinia'
defineStore('store', {
state: () => ({
toLocal: '',
toSession: '',
toNowhere: '',
}),
persist: [
{
paths: ['toLocal'],
storage: localStorage,
},
{
paths: ['toSession'],
storage: sessionStorage,
},
],
})