vuex5 Pinia插件机制
通过插件扩展
.给每个store添加公共属性 .给stores添加新的配置 .给stores添加新的方法 .包裹重用已有方法 .改变或者取消actions .应用额外的副作用像localstorage .应用给指定的store
1、使用
import { createPinia } from 'pinia'
const pinia = createPinia()
(1)定义插件
function SecretPiniaPlugin(context) {
context.pinia; ?pina实例`createPinia()`
context.app; ?vue实例`createApp()`
context.store; ? 正在配置的store
context.options; ?store的配置`defineStore()`
(1)设置响应式数据
每个store都是reactive包裹的对象,所以使用起来可直接解套ref
context.store.hello = ref('secret');
context.store.hello;
(2)state添加数据
const globalSecret = ref('secret')
可直接添加
store.secret = globalSecret
通过$state,可获得devtools追踪、ssr中进行序列化
store.$state.secret = globalSecret
添加第三方数据,不要求响应式时,需要使用markRow进行转换
store.router = markRaw(router)(3)添加监听器
? store.$subscribe(() => {
? store改变时触发
? })
? store.$onAction(() => {
? ? ?action触发时触发
? })
...
}
(2)应用插件
pinia.use(SecretPiniaPlugin)
(3)devTools能追踪修改
方式一:返回修改的操作
pinia.use(({ store }) => ({
? store.hello = 'world'
}))
方式二:显示添加
pinia.use(({ store }) => {
? store.hello = 'world'
? if (process.env.NODE_ENV === 'development') {
? ? store._customProperties.add('hello')
? }
})
2、应用
(1)给每个store添加公共state
function SecretPiniaPlugin() {
? return { secret: 'the cake is a lie' }
}
pinia.use(SecretPiniaPlugin)
(2)改写store中的action
.此例为改写成防抖action
defineStore('search', {
? actions: {
? ? searchContacts() {
? ? },
? },
? debounce: {
? ? searchContacts: 300,
? },
})
对于函数写法的store,自定义选项放入第三个参数中
defineStore(
? 'search',
? () => {
? ? ...
? },
? {
? ? // this will be read by a plugin later on
? ? debounce: {
? ? ? // debounce the action searchContacts by 300ms
? ? ? searchContacts: 300,
? ? },
? }
)
插件中:
import debounce from 'lodash/debunce'
pinia.use(({ options, store }) => {
? if (options.debounce) {
??
? ? 将设置了debounce的store中的原action改写成具有防抖功能的action
? ??
? ? return Object.keys(options.debounce).reduce((debouncedActions, action) => {
? ? ? debouncedActions[action] = debounce(
? ? ? ? store[action],
? ? ? ? options.debounce[action]
? ? ? )
? ? ? return debouncedActions
? ? }, {})
? }
})
pinia和vuex的区别
(1)它没有mutation,他只有state,getters,action【同步、异步】使用他来修改state数据
(2)他默认也是存入内存中,如果需要使用本地存储,在配置上比vuex麻烦一点
(3)语法上比vuex更容易理解和使用,灵活。
(4)pinia没有modules配置,没一个独立的仓库都是definStore生成出来的
(5)state是一个对象返回一个对象和组件的data是一样的语法
需要在页面组件中引入我们要修改数据
安装的本地存储插件可以是npm也可以是year
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于vuex5中的Pinia插件机制的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did123783