Search code examples
vue.jsquasar

How to access Vue $refs in a plugin?


methods: {  
  async create () {
    this.disableSubmit = true;
    await this.$firestore
      .collection('collectionName')
      .add(this.item)
      .then(() => {
        this.$refs.createForm.reset();
        this.$notify('positive', 'Item successfully created!');
      })
      .catch(error => {
        this.$notify('negative', 'ERROR! Try again later!', error);
      });
    this.disableSubmit = false;
  },
}

If I use the code above inside the methods property, then everything works fine, but I would like to access that ref from outside the Vue component, for example a plugin, but it gives me an error.

TypeError: "_this.$refs is undefined"

Even when I just import it as a function, the error is the same, so I would like to know how to access the ref outside vue?

Bellow is the code for my plugin, and I would also like to point that I am using the quasar framework.

export let plugin = {
  install (Vue, options) {
    Vue.prototype.$plugin = async (collection, item) => {
      return await firestore
        .collection(collection)
        .add(item)
        .then(() => {
          this.$refs.createFrom.reset();
          notify('positive', 'Booking successfully created!');
        })
        .catch(error => {
          notify('negative', 'ERROR creating booking! Try again later!', error);
        });
    };
  }
};

I hope my question makes sense, and thanks in advance for any help


Solution

  • you could pass the context of your component, to apply the reset form from your plugin:

    // plugin declaration
    Vue.prototype.$plugin = async (collection, item, ctx) {
    ...
    ctx.$refs.createFrom.reset()
    ...
    }
    

    then when u call to your plugin from yours components can do it like this:

    // your component
    methods: {
      myFunction () {
        this.$plugin(collection, item, this)
      }
    }
    

    this is the reference of the context of your current component that will be used inside of your plugin

    for example:

    Vue.component('my-form', {
      methods: {
        resetForm() {
          console.log('the form has been reset')
        }
      }
    })
    
    Vue.prototype.$plugin = (item, ctx) => {
      console.log('item passed:', item)
      ctx.$refs.refToMyForm.resetForm()
    }
    
    new Vue({
      el: '#app',
      data: {
        item: 'foo'
      },  
      methods: {
        submit() {
          this.$plugin(this.item, this)
        }
      }
    })
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    
    <div id="app">
      <my-form ref="refToMyForm"></my-form>
      <button @click="submit">submit</button>
    </div>