Ifnot
Ifnot

Reputation: 5103

VueJS make instance property reactive

I am building a VueJS plugin using instance properties and i need to bring back some reactive values back to VueJS.

My searches :

I dont understand the stuff behind Object.defineProperty(), i searched for vuex getters initialisation as my logic is similar but i dont understand how operate properly.

Simple Example :

Below a VueJS snippet attached to his prototype, main.js :

Vue.prototype.$ajax = {
  loading: false,
  isLoading () {
    return this.loading
  }
}

Now, accessing it from a component, component.vue :

export default {
    computed: {
      loading () {
        return this.$ajax.isLoading()
      }
    },
    created () {
      let self = this

      setInterval(() => {
        console.log(this.loading, this.$ajax.isLoading())
      }, 100)

      setTimeout(() => {
        this.$ajax.loading = true
      }, 1000)
    }
  }
}

Example result :

Before setTimeout we have false false (this is the expected output), but after setTimeout we have false true (the getter does not receive the modification, but the direct accesor has the value).

Any idea for bringing some reactivity stuff into my $ajax.isLoading() ?

Upvotes: 2

Views: 2257

Answers (1)

Ifnot
Ifnot

Reputation: 5103

Ok, by digging vuex code i found a solution : use a Vue instance inside the plugin with your data into in order to bring reactivity outside.

From the question :

Vue.prototype.$ajax = {
  _vm: new Vue({data: {
    loading: false
  }}),
  setLoading (loading) {
    this._vm.$data.loading = loading
  },
  isLoading () {
    return this._vm.$data.loading
  }
}

And i just changed the direct accessor by this setter on my component :

this.$ajax.setLoading(true)

Upvotes: 4

Related Questions