|
1. 写加载中组件Loading,代码如下:
<template>
<div class="loading">
数据加载中....,请稍等
</div>
</template>
<script>
export default {
name: "Loading"
}
</script>
<style>
.loading{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: rgba(67,67,67,.7);
z-index: 999;
color: white;
text-align: center;
padding-top: 150px;
}
</style>2.使用组件,难点,如何控制组件的显示,这里需要用到vuex 定义state var state = {isLoading : false}定义getters //定义getters 读取状态
var getters = {
getLoading(state){
return state.isLoading
}定义actions //定义action,要执行的操作,如流程判断,异步请求等
var actions={
loadingStart({commit}){
commit('LoadingStart'); //与mutations里的名称对应
},
loadingEnd({commit}){
commit('LoadingEnd'); //与mutations里的名称对应
}
}定义mutations //处理状态的改变
var mutations={
LoadingStart(state){
state.isLoading = true;
},
LoadingEnd(state){
state.isLoading = false;
}
}2.1 引用组件,根据vuex中的isLoading来进行显示与隐藏的控制 因为所有组件都可能会用到加载中组件,所以将它放到App组件中 注:使用mapGetters,来获取vuex中state的值,不要直接操作state 代码如下: <template>
<div id="app">
<Loading v-show="getLoading"></Loading>
<router-view/>
</div>
</template>
<script>
import Loading from './components/Loading'
import { mapGetters } from 'vuex'
export default {
name: 'App',
data(){
return {}
},
components:{
Loading
}
,
computed:mapGetters(['getLoading'])
}
</script>
<style>
</style>3.修改vuex的值,请求数据时,将isLoading变成true,数据响应成功后,isLoading变成false. 可以使用axios的拦截器,方便操作。代码如下: // 拦截Axios发起的所有请求,通过dispatch修改isLoading为true
Axios.interceptors.request.use(
config => {
vm.$store.dispatch('loadingStart'); // 显示loading组件
return config;
},
err => {
return Promise.reject(err);
});
//拦截Axios发起的所有响应,通过dispatch修改isLoading为false
Axios.interceptors.response.use((config)=>{
vm.$store.dispatch('loadingEnd');
return config
})注:这里很多小伙伴比较疑惑,那我们为什么不用sessionStrage,也可以实现组件之间的数据共享,但是,请求值改变后,组件会根据改变发生变化嘛。所以,大家记住:vuex不但实现组件间数据共享,组件也会根据值的改变而发生变化,这是很重要的一点 原创文章,转载请出处: bug收集 网址:http://bugshouji.com/shareweb/t1033 |
|
|