vue pinia 速学

86 阅读1分钟

pinia 是 vue 的状态管理工具,是 Vuex 的继任者。官网

安装

npm i pinia

yarn add pinia

pnpm add pinia

然后打开 main.ts

  1. import { createPinia } from "pinia";
  2. const pinia = createPinia();
  3. .use(pinia)

如:

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

import { createPinia } from "pinia";

const pinia = createPinia();

createApp(App)
  // .use(router)
  .use(pinia)
  .mount("#app");

入门

import { defineStore } from "pinia";

// 以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`)
export const useCounterStore = defineStore("counter", {});

这个名字(示例中的counter),它要求是独一无二的独一无二的独一无二的

第二个参数接受 Setup 函数 或 Option 对象

如果你已经学会了 Vue Setup,并且使用 Setup 模式,那么你就已经学会了 pinia。

是的 Pinia 的基础使用就是这么简单 🌚。

由于 Setup 太香了,所以

if( 第二个参数 === Option 对象 ) return;

使用

vuex 和 pinia setup 对应关系

vuexpinia setup
statereactive() 和 ref()
getterscomputed()
mutation忘了它
actionsFunction

defineStore 返回的是一个用 reactive 包装的对象。

你可以直接访问 store 中的 state、getters、actions,但是!state 与 getters 不能直接进行解构!

因为会损失其响应性。

举个 🌰:

export const useCounterStore = defineStore("这是一个独一无二的Id", () => {
  const state = reactive({ count: 1 });

  const doubleCount = computed(() => state.count * 2);

  const increment = () => ++state.count;

  return { increment, doubleCount };
});

使用:

<script setup>
const { increment, doubleCount } = useCounterStore();
</script>

此时 doubleCount 将始终只有 2,因为它失去响应性。

这时候需要使用 storeToRefs 保留其响应性:

<script setup>
import { storeToRefs } from "pinia";

const store = useCounterStore();
const { increment } = store;

const { doubleCount } = storeToRefs(store);
</script>

或者使用 computed

<script setup>
import { computed } from "vue";

const store = useCounterStore();
const { increment } = store;

const doubleCount = computed(() => store.doubleCount);
</script>

其他