看完这篇Pinia上手指南,你还会选择Vuex吗?
Vuex作为Vue前端框架官宣的状态管理工具,一直在与时俱进。然而其繁琐的actions、mutations以及模块嵌套一直饱受开发者诟病,我们始终期待着使用一款简洁的状态管理器。而Pinia的出现,去掉了模块的多层嵌套,移除了复杂的mutation操作,极大地满足了我们的诉求。
文章目录
一、安装
既然决定使用Pinia,那我们在创建Vue项目时就不要选择Vuex。然后使用npm或yarn安装pinia。
# with npm
yarn add pinia --save
# or with npm
npm install pinia --save
二、创建pinia并挂载到app上
导入createPinia,通过app.use(createPinia())即可, 也可以先赋值给变量pinia,再app.use(pinia)。
import {
createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import {
createPinia } from "pinia";
const app = createApp(App),
pinia = createPinia();
app.use(pinia).use(router).mount("#app");
三、定义store
Pinia的各个store之间是扁平化的,因此使用起来十分简洁,不像Vuex的module嵌套那么复杂。通过defineStore方法来声明一个store,传入的第一个变量为该store的id,应保证其唯一性;第二个参数为初始化配置,包含state, getters, actions等可选项, 各项都类似Vuex。值得注意的是,state为一个函数,返回一个对象,就如同vue的options API中的data选项。此外,Pinia认为mutations会增加操作复杂度,因此去除了mutations选项有多种方式可以修改state的值,甚至可以直接修改,这些将在后面介绍到。
此处由于我在创建Vue项目的时候无意选择了typescript,就顺势随便写了下interface,使用javascript的筒子可以忽略这些。
// src/store/userStore.ts
// 导入并使用defineStore来定义store
import {
defineStore } from "pinia";
interface UserState {
username: string;
password: string;
role: string;
}
export const useUserStore = defineStore("user", {
state: (): UserState => {
return {
username:"Amy",
// ...
};
},
getters: {
// ...
},
actions: {
// ...
},
});
四、store的各个属性介绍
1.state
state为一个函数,其返回值为一个对象,用于存储公共状态。对state或state的属性进行修改的行为叫做mutation。在Pinia中,不提供mutations选项。修改state的mutation行为有多种:
-
直接修改
-
// xxx.vue import { ref, computed, defineComponent } from "vue";import { useUserStore } from "@/store/userStore"; import { useUserStore } from "@/store/userStore"; export default defineComponent({ setup() { const userStore = useUserStore(); const username = computed(()=>userStore.username) userStore.username = "张三"; return { username} } })
-
-
在action里修改 (也属于直接修改)
-
先在actions声明相应的action方法,使用this可以获取store实例:
-
// src/store/userStore.ts // 导入并使用defineStore来定义store import { defineStore } from "pinia"; interface UserState { username: string; password: string; role: string; } export const useUserStore = defineStore("user", { state: (): UserState => { return { username
-