【问题标题】:VueJS Reactive Binding for a Plugin - How To?VueJS 插件的反应式绑定 - 如何?
【发布时间】:2017-01-22 13:01:56
【问题描述】:

我正在为 Pouch/CouchDB 开发一个 Vue 插件,该插件将是开源的,但只要我能找出我遇到的问题:

目前我正在尝试使该插件与 Vuex 非常相似,它具有内部状态,并检测更改,并在发生更改时呈现视图。

在 Vue 实例中,我正在初始化一个对象,并且在该对象中,我尝试使用 defineReactive 使两个或三个对象具有反应性,直到这里很好。

但是当我尝试更改该对象内的某些值时,更改不会传播到视图。但是,如果我明确调用 this.$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);
      }
    }
  }

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    我认为您不需要使用这些内部 API,例如 Vue.util.defineReactivethis.$bucket._state.projects.__ob__.dep.notify()

    因为 Vue 本身是响应式的,所以您可以使用 Vue 实例来存储数据。无需重新发明反应系统。

    在构造函数中创建一个Vue实例:

    this.storeVM = new Vue({ data })
    

    并使用 getter 将 .state 委托给 storeVM.$data

    get state () {
      return this.storeVM.$data
    }
    

    所以当你访问myPlugin.state时,你访问的是Vue实例的数据。

    我创建了一个非常简单的响应式插件示例:http://codepen.io/CodinCat/pen/GrmLmG?editors=1010

    如果 Vue 实例可以为你做所有事情,则无需使用 defineReactive 或自行通知依赖项。事实上,这就是 Vuex 的工作原理。

    【讨论】:

    • 在创建一个单独的实例只是为了拥有几个反应属性时,cpu 或内存开销是否存在任何问题?
    • @Andre12:从 vue 2.6.0 开始,你可以使用Vue.observable,这与创建一个全新的 vue 实例的开销不同。
    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2018-06-11
    • 2021-01-27
    相关资源
    最近更新 更多