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

目前,我正在try 使插件与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);
      }
    }
  }

推荐答案

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

因为Vue本身是被动的,所以可以使用Vue实例来存储数据.没有必要重新设计react 系统.

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

this.storeVM = new Vue({ data })

并使用getter将.state的任务委派给storeVM.$data

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

因此,当您访问myPlugin.state时,您正在访问Vue实例的数据.

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

如果Vue实例可以为您做任何事情,则无需使用defineReactive或自行通知依赖项.事实上,Vuex就是这样工作的.

Vue.js相关问答推荐

如何使用Nuxt 3动态处理无限嵌套路由?

Vue CDN的html工作,但v—如果不工作

VueJS使所有组件崩溃,而不是只有一个

如何在与父集合相同的读取中取回子集合(或重构数据?)

VITE:无法为VUE单文件组件加载URL

混合使用 React 和 Vue 是个好主意吗?

理解 VueJS 中的组件 props

在 jest document.querySelector 中测试 vue 组件期间始终返回 null

将检测外部点击自定义指令从 Vue 2 迁移到 Vue 3

VueJS:向左,元素的顶部位置?

使用 vee-validate 在 vue js 中进行验证有错误

VueJS + Typescript:类型上不存在属性

如何将 mapActions 与 vue + Typescript 类组件一起使用?

Vuejs 3 从子组件向父组件发出事件

重新加载页面正在 vue 组件中的插槽上闪烁内容

中文而不是英文的Element UI分页

VueJS 2 在多个组件上debounce

如何使用 Vuetify 验证复选框组

VS Code - 在 .vue 文件中启用 autoClosingTags 选项

如何在 vuejs 中的基于类的组件中编写计算设置器