How to use Toasted inside an export default {}

368 Views Asked by At

I'm trying to use the package Toasted but I'm having a hard time understading how to use it.

I have a package called TreatErrors.js and I call this package to handle all errors from my application based on HTTP code returned by API a restfull API.

TreatErrors.js

import toasted from 'vue-toasted';
export default {
  treatDefaultError(err){
    let statusCode = err.response.status;
    let data = err.response.data;
    for(let field in data.errors){
      if (data.errors.hasOwnProperty(field)) {
        data.errors[field].forEach(message => {
          toasted.show(message);
        })
      }
    }

    if(statusCode === 401){
      toastr.error('Your token has expired. Please logout and login again to retrieve a new token');
    }

    return null;
  },
}

and I'm tryin to call Toasted from within this package but I'm getting vue_toasted__WEBPACK_IMPORTED_MODULE_2___default.a.show is not a function. Any idea how I can use this Toasted inside of my own defined package?

1

There are 1 best solutions below

0
On BEST ANSWER

The vue-toasted plugin must be registered with Vue first:

import Toasted from 'vue-toasted';
Vue.use(Toasted); // <-- register plugin

Then, your module could use it via Vue.toasted.show(...):

// TreatErrors.js
export default {
  treatDefaultError(err) {
    Vue.toasted.show(err.message);
  }
}

And your Vue components could also use it via this.$toasted.show(...):

// Foo.vue
export default {
  methods: {
    showError(err) {
      this.$toasted.show(err.message);
    }
  }
}