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
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)) {
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)) {
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();
AuthStore.setButtons(availableTags);
return AuthStore.buttons
|