可以从“外部” Vue计算/监视属性吗?

我想全神贯注于Vue中的反应性,以及如何/是否可以将其用于我自己的对象以及Vue组件中未声明的其他库中对象的嵌套属性。

Here is one JS fiddle trying to use compute: http://jsfiddle.net/73r9bk2t/1/

<div id="app">
  {{item}}
</div>


var someExternalObject = { thing: 'some value' }

var vm = new Vue({
  el: '#app',
  computed: {
    item() {
      return someExternalObject.thing;
    }
  },
})

setTimeout(() => {
  someExternalObject.thing = 'new value';
  console.log(someExternalObject.thing);
}, 1000)

Here is another trying to use $watch http://jsfiddle.net/73r9bk2t/2/

<div id="app">
  {{item}}
</div>

someExternalObject = { thing: 'some initial text' }

var vm = new Vue({
  el: '#app',
  computed: {
    item() {
      return someExternalObject.thing;
    }
  },
  created()
  {
    // Give the external object a scoped reference
    this.someExternalObject = someExternalObject;

    this.$watch('someExternalObject.thing', function (newVal, oldVal)
        {
            console.log("Watched:", newVal, oldVal);
        }, { deep: true, immediate: true }); 
  }
})

setTimeout(() => {
  someExternalObject.thing = 'some updated text';
  console.log(someExternalObject.thing);
}, 1000)

但是似乎没有任何效果(文本输出未更新)。我开始怀疑我是否正在尝试做我不应该做的事情。

评论
  • 大三元
    大三元 回复

    If you're looking to integrate an external library into Vue and make it reactive then you should consider using Vue.observable. It will let you create a reactive object outside of a Vue instance.

    const state = Vue.observable({ count: 0 })
    
    const Demo = {
      render(h) {
        return h('button', {
          on: { click: () => { state.count++ }}
        }, `count is: ${state.count}`)
      }
    }

    https://vuejs.org/v2/api/#Vue-observable

    希望这可以帮助!