vue3项目使用pinia及pinia数据持久化的应用

一、项目使用pinia 

安装

1.安装项目选择pinia

//安装项目时直接选择Yes
√ Add Pinia for state management? ... No / Yes

2.下载 

npm i pinia

 在main.js中配置

import { createApp } from "vue";
//引入createPinia 
import { createPinia } from "pinia";

import App from "./App.vue";

const app = createApp(App);

//调用createPinia()
const store = createPinia();

//use store
app.use(store);

app.mount("#app");

 定义需要store数据,方法,getters

import { defineStore } from "pinia";

export const useCounterStore = defineStore("count", {
  //数据仓库
  state: () => ({
    //计数
    count: 0,
    //购物车信息
    cart: [
      { id: 1001, name: "iapd2", price: 200, num: 2 },
      { id: 1002, name: "iapd3", price: 1200, num: 12 },
      { id: 1003, name: "iapd4", price: 2300, num: 21 },
      { id: 1004, name: "iapd5", price: 2600, num: 32 },
    ],
    token: "asdf79asd0f7a9dsf7a9ds0f",
    userInfo: {
      username: "admin",
      password: "abcd",
    },
  }),
  //异步方法
  actions: {
    jia() {
      this.count++;
    },
    jian() {
      this.count--;
    },
  },
  //相当于计算属性
  getters: {
    //商品数量
    goodsNum: (state) => {
      let result = 0;
      state.cart.forEach((item) => {
        result += item.num;
      });

      return result;
    },
    //商品总价
    totalPrice: (state) => {
      const total = state.cart.reduce(
        (acc, current) => acc + current.price * current.num,
        0
      );

      return total;
    },
    //totalPrice: (state) => {},
  },
});

页面使用

<template>
  <div class="test">
    <div>测试组件--{
   
   { counterStore.count }}</div>
    <div>
      <p>商品数量:{
   
   { counterStore.goodsNum }}</p>
      <p>商品总价:{
   
   { counterStore.totalPrice }}</p>
    </div>
    <button @click="counterStore.jia">递增</button>
    <button @click="counterStore.jian">递减</button>
  </div>
</template>

<script setup>
//引入需要的pinia数据 counter.js
import { useCounterStore } from "@/stores/counter";

//生成store数据和方法
const counterStore = useCounterStore();
</script>

<style lang="scss" scoped>
.test {
  border: 1px solid #f00;
  padding: 20px;
}
</style>

二、pinia数据持久化

安装依赖

npm i pinia-plugin-persistedstate

main.js中配置依赖

import { createApp } from "vue";
//引入pinia
import { createPinia } from "pinia";

//引入pinia持久化
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";

import App from "./App.vue";

const app = createApp(App);

//实例化pinia
const store = createPinia();
//关联pinia和pinia持久化插件
store.use(piniaPluginPersistedstate);
//app关联store
app.use(store);

app.mount("#app");

在pinia开启持久化

export const useCounterStore = defineStore("count", {

  //将persist改为true,实现数据持久化
  //persist: true
  //或者将本地存储改为会话存储,实现数据持久化
  persist: {
    storage: sessionStorage,
  },
});

猜你喜欢

转载自blog.csdn.net/weixin_69370222/article/details/130194632