Vuex 的一些疑惑 vuex存在的意义
ztj100 2024-12-22 22:01 56 浏览 0 评论
store 是如何实现注入的
vuex3
Install 主要做了两件事情,第一使用闭包来防止插件重复注册,然后调用 applyMixin 方法,并传入 vue 构造函数
// src/store.js
let Vue;
export function install ( _Vue) {
// 重复注册插件的检查
if (Vue && _Vue === Vue) {
if (__DEV__) {
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
)
}
return
}
Vue = _Vue
applyMixin(Vue)
}
applyMixin 方法如下,先做版本判断,核心在于 vuexInit 方法,先判断 vue 实例中是否存在 store 属性,若存在,说明为根实例,手动将 store 属性进行挂载;若不存在,说明为根实例的 children,则取 parent 的 store 属性,总而言之,vuex3 主要利用 mixin 特性和 beforeCreate 生命周期来实现 store 属性的挂载
// src/mixin.js
export default function (Vue) {
const version = Number(Vue.version.split('.')[0])
if (version >= 2) {
// 初始化混入
Vue.mixin({ beforeCreate: vuexInit })
} else {
// override init and inject vuex init procedure
// for 1.x backwards compatibility.
const _init = Vue.prototype._init
Vue.prototype._init = function (options = {}) {
options.init = options.init
? [vuexInit].concat(options.init)
: vuexInit
_init.call(this, options)
}
}
/**
* Vuex init hook, injected into each instances init hooks list.
*/
function vuexInit () {
const options = this.$options
// store injection
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store
}
}
}
vuex4
可以看到,新版本选择使用 provide / inject 来实现 store 的设置,并且将 store 实例挂载到 app 中,同样可以全局访问
// src/store.js
import { storeKey } from './injectKey'
install (app, injectKey) {
app.provide(injectKey || storeKey, this)
app.config.globalProperties.$store = this
}
// src/injectKey.js
import { inject } from 'vue'
export const storeKey = 'store'
export function useStore (key = null) {
return inject(key !== null ? key : storeKey)
}
Vuex 如何区分 state 是外部直接修改,还是通过 mutation 方法修改的
首先,无论在 vuex3 还是 vuex4,对于 state 的直接修改会直接报错,代码如下
class Store {
set state (v) {
if (__DEV__) {
assert(false, `use store.replaceState() to explicit replace store state.`)
}
}
}
同时,如果在初始化 vuex 时,传入了 strict 选项,那么还会启动一个监听,保证 state 只能被 mutation 修改,代码如下
function enableStrictMode (store) {
watch(() => store._state.data, () => {
if (__DEV__) {
assert(store._committing, `do not mutate vuex store state outside mutation handlers.`)
}
}, { deep: true, flush: 'sync' })
}
如果 store._committing 的值为 false,上述回调将会报错,这个值的改变,只会发生在提交 mutation,在提交 commit 时,实际会调用 _withCommit 来执行修改,代码如下
_withCommit (fn) {
const committing = this._committing
this._committing = true
fn()
this._committing = committing
}
使用以上两者,就可以限制外界对于 state 的修改,只能是单一来源(mutation)
为什么 Vuex 的 mutation 中不能做异步操作
- 可预测性:mutation 是更改状态的唯一方式,确保所有状态更改都是可追踪的。如果允许异步操作,状态的变化将变得不可预测,难以调试。
- 时间旅行调试:Vuex 提供了时间旅行调试功能,即可以回溯到任意一个状态。如果 mutation 中包含异步操作,那么这个功能将无法正常工作,因为异步操作的结果无法确定。
- 严格模式:Vuex 支持严格模式,在严格模式下,任何对状态的修改都必须在 mutation 中进行。如果 mutation 中有异步操作,严格模式将无法保证状态的改变是可控的
如何使用Vuex进行状态持久化,如何使用插件
使用 vuex-persistedstate 插件,下面是一个生成 mutation 前后 state 快照的插件
const store = createStore({
plugins: [myPluginWithSnapshot],
})
const myPluginWithSnapshot = (store) => {
let prevState = _.cloneDeep(store.state)
// 这个回调在每次 mutation 之后调用
store.subscribe((mutation, state) => {
let nextState = _.cloneDeep(state)
prevState = nextState
})
}
Vuex 内部使用了 effectScope,有什么作用
先看看 vuex 内部使用 effectScope 做了什么,resetStoreState 方法的调用有两个时机,第一为手动卸载之前注册的模块,也就是外界显式调用 unregisterModule,第二则是 vuex 内部和构建工具集成的热更新逻辑,会多次调用
const resetStoreState = (store, state, hot) => {
store.getters = {}
const wrappedGetters = store._wrappedGetters
const computedObj = {}
const computedCache = {}
const oldScope = store._scope
const scope = effectScope(true)
scope.run(() => {
forEachValue(wrappedGetters, (fn, key) => {
// use computed to leverage its lazy-caching mechanism
// direct inline function use will lead to closure preserving oldState.
// using partial to return function with only arguments preserved in closure environment.
computedObj[key] = partial(fn, store)
computedCache[key] = computed(() => computedObj[key]())
Object.defineProperty(store.getters, key, {
get: () => computedCache[key].value,
enumerable: true // for local getters
})
})
})
store._scope = scope
// dispose previously registered effect scope if there is one.
if (oldScope) {
oldScope.stop()
}
}
effectScope 是 vue 3.2 引入的 api,之前,对于组件中的状态(data,computed)会随着组件的卸载而自动销毁,此 api 提供了在组件之外手动收集副作用和清除的能力
可以看到,vuex 把 getters 变成了计算属性,这时,store.getters 上面的属性,就不在依附于组件的生命周期,而是单独管理,并且在下次调用时更新
Vuex 对比 pinia
模块化方案:Vuex 使用 module 来实现状态模块化,全局只存在一个 store,会存在多级嵌套的问题,pinia 直接定义多个 store
类型支持:vuex 仍然依赖手动添加类型标注,比如使用 useStore 时,想要获取 store 的类型,需要手动注入 InjectionKey,pinia 可以自动推导
包体积:pinia 体积更小
生态:vuex 更成熟,pinia 相对较新
概念:vuex 存在 mutation 和 actions,由于所有对于 state 的变更都会通过同步的 mutation,易于调试,pinia 中的 action 则包含了同步和异步的变更,调试难度有所增加
相关推荐
- 其实TensorFlow真的很水无非就这30篇熬夜练
-
好的!以下是TensorFlow需要掌握的核心内容,用列表形式呈现,简洁清晰(含表情符号,<300字):1.基础概念与环境TensorFlow架构(计算图、会话->EagerE...
- 交叉验证和超参数调整:如何优化你的机器学习模型
-
准确预测Fitbit的睡眠得分在本文的前两部分中,我获取了Fitbit的睡眠数据并对其进行预处理,将这些数据分为训练集、验证集和测试集,除此之外,我还训练了三种不同的机器学习模型并比较了它们的性能。在...
- 机器学习交叉验证全指南:原理、类型与实战技巧
-
机器学习模型常常需要大量数据,但它们如何与实时新数据协同工作也同样关键。交叉验证是一种通过将数据集分成若干部分、在部分数据上训练模型、在其余数据上测试模型的方法,用来检验模型的表现。这有助于发现过拟合...
- 深度学习中的类别激活热图可视化
-
作者:ValentinaAlto编译:ronghuaiyang导读使用Keras实现图像分类中的激活热图的可视化,帮助更有针对性...
- 超强,必会的机器学习评估指标
-
大侠幸会,在下全网同名[算法金]0基础转AI上岸,多个算法赛Top[日更万日,让更多人享受智能乐趣]构建机器学习模型的关键步骤是检查其性能,这是通过使用验证指标来完成的。选择正确的验证指...
- 机器学习入门教程-第六课:监督学习与非监督学习
-
1.回顾与引入上节课我们谈到了机器学习的一些实战技巧,比如如何处理数据、选择模型以及调整参数。今天,我们将更深入地探讨机器学习的两大类:监督学习和非监督学习。2.监督学习监督学习就像是有老师的教学...
- Python 模型部署不用愁!容器化实战,5 分钟搞定环境配置
-
你是不是也遇到过这种糟心事:花了好几天训练出的Python模型,在自己电脑上跑得顺顺当当,一放到服务器就各种报错。要么是Python版本不对,要么是依赖库冲突,折腾半天还是用不了。别再喊“我...
- 神经网络与传统统计方法的简单对比
-
传统的统计方法如...
- 自回归滞后模型进行多变量时间序列预测
-
下图显示了关于不同类型葡萄酒销量的月度多元时间序列。每种葡萄酒类型都是时间序列中的一个变量。假设要预测其中一个变量。比如,sparklingwine。如何建立一个模型来进行预测呢?一种常见的方...
- 苹果AI策略:慢哲学——科技行业的“长期主义”试金石
-
苹果AI策略的深度原创分析,结合技术伦理、商业逻辑与行业博弈,揭示其“慢哲学”背后的战略智慧:一、反常之举:AI狂潮中的“逆行者”当科技巨头深陷AI军备竞赛,苹果的克制显得格格不入:功能延期:App...
- 时间序列预测全攻略,6大模型代码实操
-
如果你对数据分析感兴趣,希望学习更多的方法论,希望听听经验分享,欢迎移步宝藏公众号...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)