Pinia的简单使用

811 阅读1分钟

1.初始化Store

import { defineStore } from "pinia";

export const useCounterStore = defineStore({
  id: "counter",
  state: () => ({
    //state 是 store 的核心部分,数据存储
    counter: 1,
    name: "小芜湖",
  }),
  getters: {
    //Getter 完全等同于 Store 状态的 计算值
    doubleCount: (state) => state.counter * 2,
  },
  actions: {
    //可以进行一些修改state里面的数据,也可以异步请求数据
    increment(num) {
      this.counter = num;
    },
  },
});

2.如何在组件中读取到state的值

import { useCounterStore } from "./stores/counter";
const Test = useCounterStore(); //进行赋值给一个常量方便取值
//可以直接给Test中的数据进行修改
const Add = () => {
  Add是一个事件;
  Test.current++;
};
//)批量修改State的值
//在他的实例上有$patch方法可以批量修改多个值
const Add = () => {
  Test.$patch({
    current: 200,
    age: 300,
  });
};
//批量修改函数形式(state就是数据库中的数据)
//推荐使用函数形式 可以自定义修改逻辑
const Add = () => {
  Test.$patch((state) => {
    state.current++;
    state.age = 40;
  });
};
//通过原始对象修改整个实例
//$state您可以通过将store的属性设置为新对象来替换store的整个状态
//缺点就是必须修改整个对象的所有属性
const Add = () => {
  Test.$state = {
    current: 10,
    age: 30,
  };
};

3.结构store

//在Pinia是不允许直接解构是会失去响应性的
import { useCounterStore } from "./stores/counter";
const Test = useCounterStore(); //进行赋值给一个常量方便取值
const { current, name } = Test; //在Test中把常量解构出来
console.log(current, name);
//解决方案可以使用 storeToRefs
import { storeToRefs } from "pinia"; //在pinia中引入storeToRefs
const Test = useTestStore();
const { current, name } = storeToRefs(Test);
//其原理跟toRefs 一样的给里面的数据包裹一层toref

Actions

Actions跟vux中的用法一样,但是不同的是可以在内部直接this获取到state的值进行修改
//详细可以查看https://blog.csdn.net/qq1195566313/article/details/123376269?spm=1001.2014.3001.5501

getters

跟vuex一样使用, 
//详细可以查看https://blog.csdn.net/qq1195566313/article/details/123376269?spm=1001.2014.3001.5501

Api

Test.$reset(); //进行初始化
//类似于Vuex 的abscribe  只要有state 的变化就会走这个函数
Test.$subscribe((args, state) => {
  console.log(args); //第一个参数是可以拿到旧值和新值
  console.log(state); //pinia里的state的值
});
//只要有actions被调用就会走这个函数
Test.$onAction((args) => {
  console.log(args);
});

之前学习Pinia自己总结的一些笔记