vue3中 pinia 的使用方法

安装

npm install pinia

在main.ts中引入(vue3)

import { createApp } from 'vue'
import { createPinia } from "pinia";
import './style.css'
import App from './App.vue'

createApp(App).use(createPinia()).mount('#app')

1.创建store文件夹,创建 index.ts 文件

import { defineStore } from "pinia";
import { Names } from "./store_name";
export const useStore = defineStore(Names.MAIN, {
  state: () => {
    return {
      token: "",
      current: "999",
    };
  },
  // 相当于计算属性
  getters: {},
  // 相当于方法
  actions: {
    setCurrent() {
      this.current = "用actions里的方法更改值";
    },
  },
});

2.创建 pinia 的唯一值文件 store_name.ts

export const enum Names {
  MAIN = "main",
}

3.管理state的方式

// 1.直接修改
store.token = "123";

// 2.通过$patch修改
store.$patch((state) => {
  state.current = "111";
});

// 3.调用acticons里的方法修改
store.setCurrent();

4.pinia 解构不具有响应式,但是可以使用storeToRefs 来让解构的state具有响应式

import { useStore } from '../store/index'
import { storeToRefs } from 'pinia'
const store = useStore()

const { current, token } = storeToRefs(store);

5.getters 和 actions

import { defineStore } from "pinia";
import { Names } from "./store_name";
type User = {
  name: string;
  age: number;
};

const Login = (): Promise<User> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: "李子天",
        age: 80,
      });
    }, 1000);
  });
};

export const useStore = defineStore(Names.MAIN, {
  state: () => {
    return {
      token: 1,
      current: 10,
      user: <User>{},
    };
  },
  // 相当于计算属性(有缓存)
  getters: {
    getIntroduce(): string {
      const name: string = this.user.name ?? "xxx";
      const age: number = this.user.age ?? 0;
      return `我是${name},我今年${age}岁了`;
    },
    getAge(): number {
      return this.user.age;
    },
  },
  // 相当于方法
  actions: {
    // 同步
    setCurrent() {
      this.current = 5;
    },

    // 异步
    async setLogin() {
      const res = await Login();
      this.user = res;
      console.log(res);
    },
  },
});

注意:getters里的值在页面可以用{{store.getIntroduce}}插值表达式来使用

 6.api

// 监听state的api
store.$subscribe(
  (args, state) => {
    console.log(args, state);
  },
  {
    detached: true, //  组件销毁之后继续监听
    deep: true, // 深度监听
    flush: "post", // 获取“更新之后的DOM”
  }
);
// 监听actions的api
store.$onAction((args) => {
  console.log(args);
}, true); // 组件销毁之后继续监听


const btn = () => {
  // 重置state的api
  store.$reset();
};

7.持久化

npm i  pinia-plugin-persistedstate

main.ts 中引入

import { createApp } from 'vue'
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
import './style.css'
import App from './App.vue'

createApp(App).use(createPinia().use(piniaPluginPersistedstate)).mount('#app')

store文件中 index.ts 使用

import { defineStore } from "pinia";
import { Names } from "./store_name";

export const useStore1 = defineStore(Names.MAIN, {
  state: () => {
    return {
      name: "李子天",
      age: 0,
    };
  },
  getters: {},
  actions: {
    setName() {
      this.name = "李子天2";
    },
    setAge() {
      this.age = 999;
    },
  },
  // 第一种写法(持久化全部数据)
  persist: true
  // 第二种写法 (按需持久化数据)
  persist: {
    // storage: window.sessionStorage,
    paths: ["name"],
  },
});

export const useStore2 = defineStore(Names.ANOTHER, {
  state: () => {
    return {
      name: "梁延涛",
    };
  },
  getters: {},
  actions: {
    setName() {
      this.name = "梁延涛2";
    },
  },
});
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微光无限

破晓的日子还有很多!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值