面试题:是否给 Pinia 添加过插件?具体添加的方式是什么?
在 Pinia 中,我们可以为仓库添加插件,通过添加插件能够扩展以下的内容:
- 为 store 添加新的属性
- 定义 store 时增加新的选项
- 为 store 增加新的方法
- 包装现有的方法
- 改变甚至取消 action
- 实现副作用,如本地存储
- 仅应用插件于特定 store
自定义插件
首先建议插件单独拿一个目录来存放,一个插件就是一个方法:
export function myPiniaPlugin1() {
// 给所有的仓库添加了一条全局属性
return {
secret: "the cake is a lie",
};
}
export function myPiniaPlugin2(context) {
// console.log(context);
const { store } = context;
store.test = "this is a test";
}
/**
* 给特定的仓库来扩展内容
* @param {*} param0
*/
export function myPiniaPlugin3({ store }) {
if (store.$id === "counter") {
// 为当前 id 为 counter 的仓库来扩展属性
return {
name: "my name is pinia",
};
}
}
/**
* 重置仓库状态
*/
export function myPiniaPlugin4({ store }) {
// 我们首先可以将初始状态深拷贝一份
const state = deepClone(store.$state);
store.reset = () => {
store.$patch(deepClone(state));
};
}
每个插件在扩展内容时,会对所有的仓库进行内容扩展,如果想要针对某一个仓库进行内容扩展,可以通过 context.store.$id 来指定某一个仓库来扩展内容。
插件书写完毕后,需要通过 pinia 实例对插件进行一个注册操作。
// 引入自定义插件
import {
myPiniaPlugin1,
myPiniaPlugin2,
myPiniaPlugin3,
myPiniaPlugin4,
} from "./plugins";
pinia.use(myPiniaPlugin1);
pinia.use(myPiniaPlugin2);
pinia.use(myPiniaPlugin3);
pinia.use(myPiniaPlugin4);
添加第三方插件
有一些第三方插件,直接通过 npm 安装使用即可。
具体的使用方法一定要参阅文档。
真题解答
题目:是否给 Pinia 添加过插件?具体添加的方式是什么?
参考答案:在 Pinia 中可以非常方便的添加插件。一个插件就是一个函数,该函数接收一个 context 上下文对象,通过 context 对象可以拿到诸如 store、app 等信息。
每个插件在扩展内容时,会对所有的仓库进行内容扩展,如果想要针对某一个仓库进行内容扩展,可以通过 context.store.$id 来指定某一个仓库来扩展内容。
插件书写完毕后,需要通过 pinia 实例对插件进行一个注册操作。
另外,我们还可以使用一些第三方插件,直接通过 npm 安装使用即可。安装完毕后,使用方法和自定义插件是一样的,具体的使用方法一定要参阅文档。