Vue通过状态为页面切换添加loading、为ajax加载添加loading
以下方法需要引入vuex,另使用了vux的UI框架,ajax添加loading还引入了axios。
一、为页面切换添加loading。
loading.js:
import Vue from 'vue' import Vuex from 'vuex' import router from './router' Vue.use(Vuex) const store = new Vuex.Store({}) // 这里你可能已经有其他 module store.registerModule('myVux', { // 名字自己定义 state: { isLoading: false }, mutations: { updateLoadingStatus (state, payload) { state.isLoading = payload.isLoading } } }) router.beforeEach(function (to, from, next) { store.commit('updateLoadingStatus', {isLoading: true}) next() }) router.afterEach(function (to) { store.commit('updateLoadingStatus', {isLoading: false}) }) export default store;
main.js
import Vue from 'vue' import Vuex from 'vuex' import App from './App' import router from './router' import store from './loading' Vue.use(Vuex) Vue.use(router) new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
App.vue:
//在模板中加入以下vux组件 <loading :text="loadText" v-model="isLoading"></loading> import { Loading } from 'vux' import { mapState } from 'vuex' export default { name: 'app', data(){ return { loadText:"loading" } }, components: { Loading }, computed:{ ...mapState({ isLoading: state => state.myVux.isLoading }) } }
二、为ajax添加loading(发送请求时显示,返回数据时消失)。
loading.js:
import Vue from 'vue'
import Vuex from 'vuex'
import Axios from 'axios'
Vue.use(Vuex)
Axios.interceptors.request.use(config => {
console.log('ajax begin request')
store.commit('ajaxStar')
return config;
})
Axios.interceptors.response.use(config => {
console.log('ajax get response')
store.commit('ajaxEnd')
return config
})
store.registerModule('myVux', { // 名字自己定义
state: {
ajaxIsLoading: false
},
mutations: {
ajaxStar (state) {
state.ajaxIsLoading = true
},
ajaxEnd (state) {
state.ajaxIsLoading = false
}
},
getter : {
ajaxIsLoading: state => state.ajaxIsLoading
}
})
export default store;
main.js
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import router from './router'
import store from './loading'
Vue.use(Vuex)
Vue.use(router)
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: {
App
}
})
App.vue:
//在模板中加入以下vux组件
<loading :text="loadText" v-model="ajaxIsLoading"></loading>
import { Loading } from 'vux'
import { mapState } from 'vuex'
export default {
name: 'app',
data(){
return {
loadText:"loading"
}
},
components: {
Loading
},
computed:{
...mapState({
ajaxIsLoading: state => state.myVux.ajaxIsLoading
}) } }