使用vuex在vue + vant 專案中加 loading載入
阿新 • • 發佈:2019-02-09
由於專案需要,參考網上例子,自己動手寫了一個,廢話不多說,上程式碼。
在src目錄下新建store目錄,store目錄下新建store.js檔案 (已確保已裝好vuex)
import Vue from 'vue' import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { LOADING: false }, mutations: { showLoading(state){ state.LOADING = true }, hideLoading (state) { state.LOADING = false } } }) export default store
<template> <div class="loading"> <img src="./../assets/img/loading.gif" alt=""> </div> </template> <script> export default { name: 'LOADING', data () { return {} }, } </script> <style scoped> .loading{ position: fixed; top:0; left:0; z-index:121; width: 100%; height: 100%; background: rgba(0,0,0,0.3); display: table-cell; vertical-align: middle; text-align: center; } .loading img{ width: 1rem; height: 1rem; margin:7.5rem auto; } </style>
在app.vue中使用loading元件
<template> <div id="app" class="app"> <loading v-show="LOADING"></loading> <router-view/> </div> </template> <script> import {mapState} from 'vuex' import Loading from './views/loading.vue' export default { computed:{ ...mapState([ 'LOADING' ]) }, name: 'App', components: { Loading, } } </script> <style> #app { font-family: Helvetica, sans-serif; height: 100%; } </style>
然後main.js
import store from './store/store'
Vue.use(moment);
Vue.use(Vant)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router,
store
}).$mount('#app')
如果需要在請求封裝中使用在請求中加
axios.interceptors.request.use(
config => {
store.commit('showLoading')
error => {
store.commit('hideLoading')
})
axios.interceptors.response.use(
response => {
store.commit('hideLoading')
},
error => {
store.commit('hideLoading')
}
);
如在單個請求中使用,在 請求時 中加
this.$store.commit('showLoading')
請求完成後加
this.$store.commit('hideLoading')
有問題可以問,有時間必回