学习的目标
- Pinia 的整体架构是怎样
- 学习原理,如何缓存数据
Pinia 的整体架构
问题
vue3 中的 markRaw 的作用
将一个响应式对象/对象转为普通对象,并且标记不可被转为代理
vue3 中的 effectScope 的作用
生成一个临时的作用域空间,在这作用域空间下使用的 ref, watch, watchEffect 等工具,当着作用域要销毁时,里面的响应式都会随之而销毁
简单来说,就是帮你创建一个临时的作用域,让你不需要处理里面的响应式的销毁时刻,响应式会随作用域自动销毁
代码演示:
const scope = effectScope();
const state = scope.run(() => {
const b = ref(2);
watch(b, () => {
console.log("update b", b.value);
});
return {
a: 1, b };
});
state.b.value += 1; // 触发日志 update b
setTimeout(() => {
scope.stop();
state.b.value = 0; // 不会触发日志
}, 100);
为什么 Pinia 要使用 effectScope?
统一收集各个 store 的响应式,可以在同一个时刻下对各个 store 进行销毁处理
Pinia 是如何实现不需要额外定义 TypeScript 类型
vuex 的 TypeScript 定义
vuex@4 还是需要额外的定义 state 的类型:
// store.ts
import {
InjectionKey } from 'vue'
import {
createStore, Store } from 'vuex'
// define your typings for the store state
export interface State {
count: number
}
// define injection key
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state: {
count: 0
}
})
// main.ts
import {
createApp } from 'vue'
import {
store, key } from './store'
const app = createApp({
... })
// pass the injection