vue3(笔记)5.0--pinia工具的知识扩展

pinia工具

defineStore(创建pinia)

  • 作用:用于定义一个 Pinia store。

  • 用法

    • 接收一个唯一的 ID 和一个配置对象,配置对象中可以定义 stategetters 和 actions
    • state 是一个函数,返回初始状态。
    • getters 类似于 Vue 组件中的计算属性,用于派生状态。
    • actions 用于修改状态和执行异步操作。

示例代码:

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
  },
});

 storeToRefs(响应式数据)

  • 响应式绑定:确保模板中的绑定能够响应 store 状态的变化。
  • 解构便利:允许你解构 store 的状态,同时保持响应式特性。
  • 避免不必要的重新渲染:通过只解构需要的状态,可以减少不必要的重新渲染。

示例代码:

插件系统

pinia持久化数据可查看上一章节


$subscribe 和 $onAction(监听store数据)

  • $subscribe

    • 作用:允许你订阅 store 的状态变化,并在状态发生变化时触发回调函数。
    • 用法:在 store 实例上调用 $subscribe 方法,传入一个回调函数,回调函数接收两个参数:mutation 和 state
  • $onAction

    • 作用:允许你监听 store 中 actions 的调用,并在 action 调用前后执行逻辑。
    • 用法:在 store 实例上调用 $onAction 方法,传入一个回调函数,回调函数接收一个包含 action 名称、args 参数等信息的对象。

示例代码:

import { useCounterStore } from '@/stores/counter';

export default {
  setup() {
    const store = useCounterStore();

    // 订阅状态变化
    store.$subscribe((mutation, state) => {
      console.log('State changed:', mutation, state);
    });

    // 监听 action 调用
    store.$onAction(({ name, args }) => {
      console.log(`Action ${name} called with args:`, args);
    });

    return {
      store,
    };
  },
};

 与 Vue Router 集成

  • 作用:Pinia 可以与 Vue Router 集成,以便在路由变化时执行特定的逻辑,如加载数据或重置状态。

  • 用法

    • 在路由守卫中访问和修改 Pinia store 的状态。
    • 使用 store 的 actions 在路由变化时执行异步操作。

示例代码:

import { useCounterStore } from '@/stores/counter';
import { onBeforeRouteUpdate } from 'vue-router';

export default {
  setup() {
    const store = useCounterStore();

    onBeforeRouteUpdate((to, from, next) => {
      // 在路由变化时执行逻辑
      store.reset(); // 假设 store 有一个 reset 方法
      next();
    });

    return {
      store,
    };
  },
};

你可能感兴趣的:(vue3,笔记)