vue3+Pinia+ts的用法

Pinia 的用法

说明书
它没有mutation ,只有state 、getters、actions,快速上手,比vuex用法要简单。

一个 Store (如
Pinia)是一个实体,它持有未绑定到您的组件树的状态和业务逻辑。换句话说,它托管全局状态。它有点像一个始终存在并且每个人都可以读取和写入的组件。它有三个概念,state、getters
和 actions 并且可以安全地假设这些概念等同于组件中的“数据”、“计算”和“方法”。

在这里插入图片描述
Pinia
第一步下载

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,
    },
  ],
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值