Pinia.js是新一代的状态管理器,即Vux5.x
特点:
1.完整的ts支持。
2.轻量,压缩后只有1.6kb。
3.去除mutations,只有state,getters,actions
4.actions支持同步和异步。
5.没有模块嵌套,只有store的概念,store之间可以自由使用。
6.无需手动添加store,store一旦常见便会自动添加。
安装
yarn add pinia -S
yarn add pinia-plugin-persist -S 数据持久化工具。
由于理念为更好的支持代码切割,所以按照功能分文件: index.ts、auth.ts、其他功能模块。
index.ts
// 使用pinia
import { createPinia } from "pinia";
import piniaPersist from "pinia-plugin-persist";
const store = createPinia();
store.use(piniaPersist);
export default store;
auth.ts
import { defineStore } from "pinia";
interface AuthState {
buttons: string[];
}
export const authStore = defineStore({
id: "auths",
state: (): AuthState => {
return {
buttons: [],
};
},
// 数据持久化-缓存
persist: {
enabled: true,
},
actions: {
// 判断按钮是否有权限
setButtons(payload: string[]) {
console.log({ payload });
this.buttons = [...payload];
},
},
});
在main.js中引入
import store from "./store";
import piniaPersist from "pinia-plugin-persist";
const app = createApp(App);
store.use(piniaPersist);
app.use(store);
鉴权自定义指令文件,src/directives/index.ts
import { App, nextTick } from "vue";
import { authStore } from "@/store/auth";
// 自定义指令,用于判断按钮权限
export default function directive(app: App) {
app.directive("auth", {
created: (el, binding) => {
let userStore: any = authStore();
const btns: string[] = userStore.buttons || [];
if (!btns.includes(binding.value)) {
// 官网说inserted()不保证插入,若还未插入,remove函数无效
// 这里使用Vue.nextTick() 函数来保证dom已插入
nextTick(() => el.remove());
}
},
});
app.directive("bgColor", {
beforeMount: (el, binding) => {
el.style.backgroundColor = binding.value;
},
});
}
注意⚠️:
import { authStore } from "@/store/auth";
let userStore: any = authStore();
const btns: string[] = userStore.buttons || [];
// 自定义指令,用于判断按钮权限
export default function directive(app: App) {
app.directive("auth", {
created: (el, binding) => {
if (!btns.includes(binding.value)) {
// 官网说inserted()不保证插入,若还未插入,remove函数无效
// 这里使用Vue.nextTick() 函数来保证dom已插入
nextTick(() => el.remove());
}
},
});
app.directive("bgColor", {
beforeMount: (el, binding) => {
el.style.backgroundColor = binding.value;
},
});
}
如果在全局饮用注册,会报错getActivePinia was called with no active Pinia. Did you forget to install pinia?
在vue中使用:
import { authStore } from "@/store/auth";
const AuthStore = authStore();
//之前vuex中commit写法改为:
AuthStore.setButtons(availableTags);
//从state中获取数据改为:
return AuthStore.buttons