2

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() ?

0

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I was also looking for this exact solution, although it looks pretty ugly...
Nah it make sense. We need a "reactive data holder" if our data is outside VueJs. Moreover VueJs instanciation is very light, so we can make as many VueJs instance as we want for this kind of usage.
Not bad, though Vue.observable is a cleaner way of doing this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.