我正在为Pouch/CouchDB开发一个Vue插件,它将是开源的,但只要我能解决我遇到的问题:
目前我正在尝试使插件与Vuex紧密相似,具有内部状态,并检测更改,并在发生时呈现视图.
在Vue实例中我正在初始化一个对象,并且在该对象中,我试图使用defineReactive使两个或三个对象反应,直到这里它是好的.
但是当我尝试更改该对象内的某些值时,更改不会传播到View.但是,如果我明确地调用它.$ bucket._state.projects .__ ob __.dep.notify(),变化传播.
Vue实例的当前对象表示如下: Vue { $bucket: { _state: { projects: {} } } }
$bucket._state已初始化defineReactive.我相信它应该有效,但我不确定在这种情况下究竟是什么问题.
任何的想法?
部分代码,这里的类几乎相似 Vuex.Store({})
constructor(schema = {}) {
// Getting defineReactive from Vue
const { defineReactive } = Vue.util;
// Ignored Schema Keys
const ignoredKeys = [
'config',
'plugins'
];
// Internal Variables
this._dbs = {};
// Define Reactive Objects
defineReactive(this, '_state', {});
defineReactive(this, '_views', {});
// Local Variables
if (!schema.config) {
throw new Error(`[Pouch Bucket]: Config is not declared in the upper level!`);
}
// Init PouchDB plugins
if ((schema.plugins.constructor === Array) && (schema.plugins.length > 0)) {
for (let i = 0; i < schema.plugins.length; i++) {
PouchDB.plugin(
schema.plugins[i]
);
}
}
// Initializing DBs that are declared in the schema{}
for (const dbname in schema) {
if (schema.hasOwnProperty(dbname) && ignoredKeys.indexOf(dbname) === -1) {
this._initDB(
dbname,
Object.assign(
schema.config,
schema[dbname].config ? schema[dbname].config : {}
)
);
this._initState(dbname);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*Cat 14
我没有深入研究这个想法,但我认为你不需要像Vue.util.defineReactive或那样使用这些内部APIthis.$bucket._state.projects.__ob__.dep.notify()
因为Vue本身是被动的,所以您可以使用Vue实例来存储数据,而无需重新发明反应系统.
在构造函数中创建实例:
this.storeVM = new Vue({ data })
Run Code Online (Sandbox Code Playgroud)
并使用getter委托.statetostoreVM.$data
get state () {
return this.storeVM.$data
}
Run Code Online (Sandbox Code Playgroud)
因此,当您访问时myPlugin.state,您正在访问Vue实例的数据.
我创建了一个非常简单的反应式插件示例:http://codepen.io/CodinCat/pen/GrmLmG?edit = 1010
无需defineReactive或自己通知的依赖关系,如果Vue的实例可以为你做的一切.事实上,这就是Vuex的工作原理.
| 归档时间: |
|
| 查看次数: |
2771 次 |
| 最近记录: |