如何在 Vuex 中存储非反应性数据?
How to store non-reactive data in Vuex?
我有数据,在 VueJS 应用程序初始化之前在页面上加载过一次,并且此数据不会一直更改,而 html 页面不会重新加载(经典 CGI 应用程序,不是 SPA)。数据示例:
const nonReactiveObjectWithSomeNestedData = {
a: 'a',
b: {
bb: 'bb',
cc: { ccc: 'ccc' },
dd: ['dd1', 'dd2']
}
}
我在几个 vue 组件中使用这些数据。将此数据存储在 Vuex 命名空间模块中并使用 Vuex-getters 为不同的 vue 组件包装相同的功能会很方便。有什么方法可以不在 vuex state
中存储这些数据(不需要反应性)但能够从 vuex-module 的 getter?
访问
PS.目前我正在使用存储非反应性数据inside vue-instance方法,但现在还不够,我需要更多的全局访问权限数据(来自两个独立的根组件)。
在将对象添加到存储之前冻结该对象:
Object.freeze(nonReactiveObjectWithSomeNestedData )
Vue 不会使冻结的对象具有反应性。
注意: 你应该在对象进入 Vuex 之前冻结它 mutation/action:
this.$store.dispatch('moduleName/setNonReactiveObject',
Object.freeze(nonReactiveObjectWithSomeNestedData));
在突变函数内部,有效载荷参数已经是反应性的。
也可以向对象添加 属性 _isVue
以避免使其反应。
commit('setNonReactiveObject', Object.assign(data, { _isVue: true })
当无法控制数据在存储中的存储方式时,此方法可用于生成数据 non-reactive。例如,当商店数据被 client-side 完全替换为 "hydrate" 时,一个 server-side 呈现的网站(例如 Nuxt)。
这没有记录在案,将来可能会崩溃。
至少 source code has a comment indicating that this property is used for this internally. And here 是在 观察 对象之前检查 属性 的地方。
我可以通过这样的操作删除 "reactiveness"
// create new variable and remove reactiveness, does a deep clone
var someNewNonReactiveVar = JSON.parse(JSON.stringify(someReactiveVar));
在变异文件中,您可以深度克隆您不想反应的负载
import _ from 'lodash';
[mutationTypes.SET_INITIAL_STATE](state, payload) {
// In order to make sure that this property is non-reactive deep clone it
state.initialState = _.cloneDeep(payload)
}
这样 initialState 或您要添加到状态的任何 属性 都不会反应。
我有数据,在 VueJS 应用程序初始化之前在页面上加载过一次,并且此数据不会一直更改,而 html 页面不会重新加载(经典 CGI 应用程序,不是 SPA)。数据示例:
const nonReactiveObjectWithSomeNestedData = {
a: 'a',
b: {
bb: 'bb',
cc: { ccc: 'ccc' },
dd: ['dd1', 'dd2']
}
}
我在几个 vue 组件中使用这些数据。将此数据存储在 Vuex 命名空间模块中并使用 Vuex-getters 为不同的 vue 组件包装相同的功能会很方便。有什么方法可以不在 vuex state
中存储这些数据(不需要反应性)但能够从 vuex-module 的 getter?
PS.目前我正在使用存储非反应性数据inside vue-instance方法,但现在还不够,我需要更多的全局访问权限数据(来自两个独立的根组件)。
在将对象添加到存储之前冻结该对象:
Object.freeze(nonReactiveObjectWithSomeNestedData )
Vue 不会使冻结的对象具有反应性。
注意: 你应该在对象进入 Vuex 之前冻结它 mutation/action:
this.$store.dispatch('moduleName/setNonReactiveObject',
Object.freeze(nonReactiveObjectWithSomeNestedData));
在突变函数内部,有效载荷参数已经是反应性的。
也可以向对象添加 属性 _isVue
以避免使其反应。
commit('setNonReactiveObject', Object.assign(data, { _isVue: true })
当无法控制数据在存储中的存储方式时,此方法可用于生成数据 non-reactive。例如,当商店数据被 client-side 完全替换为 "hydrate" 时,一个 server-side 呈现的网站(例如 Nuxt)。
这没有记录在案,将来可能会崩溃。 至少 source code has a comment indicating that this property is used for this internally. And here 是在 观察 对象之前检查 属性 的地方。
我可以通过这样的操作删除 "reactiveness"
// create new variable and remove reactiveness, does a deep clone
var someNewNonReactiveVar = JSON.parse(JSON.stringify(someReactiveVar));
在变异文件中,您可以深度克隆您不想反应的负载
import _ from 'lodash';
[mutationTypes.SET_INITIAL_STATE](state, payload) {
// In order to make sure that this property is non-reactive deep clone it
state.initialState = _.cloneDeep(payload)
}
这样 initialState 或您要添加到状态的任何 属性 都不会反应。