Vue經過狀態爲頁面切換添加loading、爲ajax加載添加loading

如下方法須要引入vuex,另使用了vux的UI框架,ajax添加loading還引入了axios。vue

 

1、爲頁面切換添加loading。ios

  loading.js:ajax

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.jsvuex

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:axios

//在模板中加入如下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
      })
    }
  }

 

 

2、爲ajax添加loading(發送請求時顯示,返回數據時消失)。app

  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.jsspa

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:code

//在模板中加入如下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}) } }
相關文章
相關標籤/搜索