在vue项目中自定义组件实现异步请求数据,在获取到数据之前有一个loading的动态图,使界面更友好

在这里定义一个loading组件:

loading.vue:

<template>
    <div class="loading-img">
        <img src="../../assets/loading.gif" alt="">
    </div>
</template>

<script>
export default {
    name:'loading'
}
</script>

<style lang="less" scoped>
.loading-img{
     position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        top: 0;
        width: 100px;
        height: 100px;
        margin: auto;
    img{
        width: 100px;
        height: 100px;
    }
    
}
</style>

在home页面使用:

<template>
    <div>
        <h1>home</h1>
        <Loading class="loading" v-if="loading"></Loading>
    </div>
    
</template>

<script>
import Loading from '../components/loading.vue'
import {mapState} from 'vuex'
export default {
    name: 'home',
    data(){
        return {
            isLoading: false
        }
    },
    beforeCreate(){
        document.querySelector('body').setAttribute('style', 'background-color:#fff')
    },
    beforeDestroy(){
        document.querySelector('body').removeAttribute('style')
    },
    mounted(){
        this.$store.state.loading = true
        this.$store.dispatch('getNews')
    },
    components:{Loading},
    computed:{
        ...mapState([
            'loading'
        ])
    }
}
</script>

<style lang="less" scoped>
body{
    background: red;
    position: relative;
}
</style>


store.js:

import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state:{
        newsList: [],
        loading: false
    },
    mutations:{
        setNews(state,{newsList}){
            state.newsList = newsList
        }
    },
    actions: {
        getNews(store){
            setTimeout(()=>{
                axios.get('/109-35'+'?showapi_appid=73783&showapi_sign=c870408835214a0eacca959aba6f317f').then(res=>{
                    store.state.loading = false  //请求到数据后,loading图消失
         
                })
            },2000)
           
        }
    }
})

原理:

在vuex中使用一个loading变量来记录动态图的状态,通过开始请求数据和请求到数据这两种状态的改变,来控制动态图的显示与否

Logo

前往低代码交流专区

更多推荐