vue中如何实现局部刷新效果

请求拦截器和响应拦截器

1.新增一个http.js文件,配置axios响应拦截器和请求拦截器。然后再导入Loading组件。并设置startLoading和endLoading两个函数,作用就是如函数名所示了。

import axios from 'axios'
import { Message, Loading } from 'element-ui'

let loading

function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '为小主拼命加载中...',
        background: 'rgba(0,0,0,7)'
    })
}

function endLoading() {
    loading.close()
}

// 请求拦截
axios.interceptors.request.use(config => {
    startLoading()
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use( response => {
    endLoading()
    return response
}, error => {
    endLoading()
    Message.error(error.response.data)
    return Promise.reject(error)
})


export default axios

main.js中引入http.js并绑定在vue上

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

// 引入刚才写的请求拦截
import axios from './http'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false

Vue.use(ElementUI);

// 绑定axios在vue属性上
Vue.prototype.$axios = axios


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

猜你喜欢

转载自blog.csdn.net/qq_21161977/article/details/112390289