artemsky / vue-snotify

Vuejs 2 Notification Center
https://artemsky.github.io/vue-snotify/
MIT License
795 stars 98 forks source link

Use snotify in js files #63

Open njordr opened 6 years ago

njordr commented 6 years ago

Hey

I'm using vue-element-admin in my project. It has an util dir with request.js file in it to make http request easier:

import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['SPYREST-TOKEN'] = getToken()
  }
  return config
}, error => {
  // Do something with request error
  this.$log.error('Request error', error.response.status, error)
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => response,
  error => {
    this.$log.error('Request error', error.response.status, error)
    if (error.response.status === 401) {
      store.dispatch('FedLogOut').then(() => {
        location.reload()
      })
    } else {
      return Promise.reject(error)
    }
  })

export default service

There is a file (main.js) at the source root that import snotify and it works for the rest of the app.

But I want to notify the user if the REST endpoint is down, this means I have to use snotify in request.js

I tried to use snotify importing Vue object:

import Vue from 'vue'

Vue.Snotify.warn(...)

but $snotify is undefined

I tried to create a js file (utils/notifier.js):

import Snotify from 'vue-snotify'
import Vue from 'vue'

Vue.use(Snotify, {
  toast: {
    timeout: 4000,
    showProgressBar: true,
    closeOnClick: true,
    pauseOnHover: true
  }
})

const snotify = Vue.$snotify

export default snotify

importing it in request.js, but with the same result

Could you please tell me how to do?

b1ack-ange1 commented 6 years ago

You can use Vue eventBus. Just create vue component errorHandler and in his created() method subscribe to global event. For Example "HANDLE_ERROR". And in your interceptor error handler function you emit event: Vue.$emit("HANDLE_ERROR", error)

In vue component you can use snotify as you want.

nros commented 6 years ago

For the impatient, I see two more options:

njordr commented 6 years ago

Hey, sorry for the late reply.

@nros using it directly works like a charm, thanks!