How can I put toast messages in a separate file when unsing Vue.js

3.4k Views Asked by At

I'm using Vue.js and I have toast messages that are hard coded in the 'main.js' and needs to be moved to another separate file. I tried using an external file and importing vue and the needed file for that purpose but failed to make it work.

I also like to note that the toasts are registered in main.js and not in a component. Here's the separate file's code

import Vue from 'vue'
import Toasted from 'vue-toasted'
Vue.use(VuePreview)
Vue.use(Toasted)
Vue.toasted.register('loginError', 'Wrong Email or password!', {
  type: 'error',
  duration: 2000
})
Vue.toasted.register('noInternet', 'No Internet Connection!', {
  type: 'error',
  duration: 2000
})
Vue.toasted.register('unknownError', 'Something went wrong!', {
  type: 'error',
  duration: 2000
})
1

There are 1 best solutions below

2
On BEST ANSWER

Create an external file and import that file into your main.js.

toasts.js

import Vue from 'vue'
import Toasted from 'vue-toasted'

Vue.toasted.register('loginError', 'Wrong Email or password!', {
  type: 'error',
  duration: 2000
})
Vue.toasted.register('noInternet', 'No Internet Connection!', {
  type: 'error',
  duration: 2000
})
Vue.toasted.register('unknownError', 'Something went wrong!', {
  type: 'error',
  duration: 2000
})

main.js

import Vue from 'vue'
import App from './App'
import "./toasts"


new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

Then you can use the registered toasts like this in Vue:

this.$toasted.global.loginError()
this.$toasted.global.noInternet()
this.$toasted.global.unknownError()

Here is a working example.