2

I am trying to wrap my head around the reactivity in Vue and how/if I can use it in regard to nested properties in objects from my own and other libraries that are not declared within the Vue components.

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)

But nothing seems to work (text output is not updated). I am starting to wonder if I am trying to do something that I shouldn't do.

Solsiden
  • 673
  • 1
  • 7
  • 22
  • *do something that I shouldn't do* - you probably do. Can be XY problem. Consider explaining your real case and specify the lib you need to integrate with. Even if your original question will be answered, it's unnecessary that it will work for you. – Estus Flask Apr 24 '20 at 14:48

2 Answers2

2

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://v2.vuejs.org/v2/api/#Vue-observable

Hope this helps!

tony19
  • 125,647
  • 18
  • 229
  • 307
Shadskii
  • 321
  • 2
  • 4
  • Perfect, I see I can define the particular nested properties I want to be observable with this (avoiding observing everything). Thank you! – Solsiden Apr 24 '20 at 15:20
0

In Vue 3 you can use ref() or reactive():

import { reactive } from 'vue';
const state = reactive({ count: 0 });

Relevant links:

Kristofer
  • 675
  • 7
  • 15