vue3 状态管理工具 pinia 使用

1、安装pinia

npm install pinia --save

2、创建 Store

新建一个 store 文件,创建 index.ts

import { createPinia } from "pinia";
const store = createPinia();
export default store;

3、在main.ts里全局引入

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store"; // 引入 

const app = createApp(App);
app.use(router);
app.use(store); // 注册
app.mount("#app");

4、定义一个store

在 store 文件里建一个 counter.ts ,定义该状态管理,可根据自己项目建多个

import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
  state: () => {   // 数据
    return { 
      count: 0,
      msg: "我cao",
      todoList: ["111", "222"],
    };
  },
  getters: {
    doubleCount(state: any): number {   // 计算
      return state.count * 2;
    },
  },
  actions: {
    increment(payload?: number) {   // 方法
      this.count = payload ? this.count + payload : this.count + 1;
    },
  },
});

5、访问State




你也可以使用storeToRefs进行解构  




defineComponent 模式下的使用




6、修改状态数据 

1、直接修改和批量修改




2、批量修改  $patch




3、重置 $reset ,可把参数重置回原始参数

counterStore.$reset()

4、替换 $state ,也只能换原有的参数,和批量修改差不多

counterStore.$state = { counter: 666, msg: "Paimon", todoList: [] };

5、监听 state 数据变化 

counterStore.$subscribe((mutation: any, state: any) => {
  // 订阅 state 值的变化
  console.log("cart:" + JSON.stringify(state));
});

你可能感兴趣的:(vue3,pinia,vue.js,前端,javascript)