使用vuex在vue2.x + vant 项目中加 loading加载
由于项目需要,参考网上例子,自己动手写了一个,废话不多说,上代码。在src目录下新建store目录,store目录下新建store.js文件 (已确保已装好vuex)import Vue from 'vue'import Vuex from 'vuex';Vue.use(Vuex);const store = new Vuex.Store({state: {...
·
由于项目需要,参考网上例子,自己动手写了一个,废话不多说,上代码。
vue3.0版本(使用vuex在vue3.0 + vant 项目中的 loading加载)
在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
loading组件如下:(图片建议网上找无背景的图)附我用的图(http://img.lanrentuku.com/img/allimg/1212/5-121204193R0-50.gif)或 使用vant中loading 加载(详细属性见vant中loading)
<template>
<div class="loading">
<img src="./../assets/img/loading.gif" alt="">
<van-loading class="loadingVant" vertical type="spinner">加载中...</van-loading>
</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(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')
有问题可以评论,有时间必回
更多推荐
已为社区贡献9条内容
所有评论(0)