【问题标题】:How to run ajax process first before calling slider on vue component?如何在 vue 组件上调用滑块之前先运行 ajax 进程?
【发布时间】:2017-12-28 22:34:20
【问题描述】:

我的顶级联赛组件 vue 是这样的:

<template>
    <div class="row">
        <div class="col-md-3" v-for="item in items">
             <div class="panel panel-default">
                <div class="panel-image">
                    <a :href="baseUrl+'/leagues/'+item.id+'/'+item.name"
                        :style="{backgroundImage: 'url(' + baseUrl + '/img/leagues/'+item.photo+ ')'}">
                    </a>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    ...
    export default {
        ...
        props: ['leagueId'],
        mounted(){
            setTimeout( function(){  
                $('.slick').not('.slick-initialized').slick({slidesToShow: 3, infinite: false});
            }  , 10000 );
        },
        created() {
            this.getTopLeague([{league_id: this.leagueId}]) // this is ajax if load first
        },
        computed: {
            ...mapGetters([
                'getListLeague'
            ]),
            items() {
                const n = ['getListLeague']
                return this[n[0]] // this is response ajax // exist 5 league
            }
        },
        methods: {
            ...mapActions([
                'getTopLeague'
            ])
        }
    }
</script>

第一次加载时,有5项数据以滑块的形式显示。滑块工作。我使用 setTimeout。但是,这似乎不是一个有效的方法。因为ajax进程有时要10秒才能完成。有时只有2-5秒。这是不确定的。

有没有更好的办法?

【问题讨论】:

    标签: vue.js slider vuejs2 vue-component vuex


    【解决方案1】:

    mapActions maps your actions to store.dispatch,其中returns a promise。您应该能够简单地等待承诺解决,然后进行回调:

    export default {
        ...
        props: ['leagueId'],
        created() {
            this.getTopLeague([{league_id: this.leagueId}])
                .then(function(){  
                    $('.slick').not('.slick-initialized').slick({slidesToShow: 3, infinite: false});
                })
        },
        ...
    

    【讨论】:

    • 存在错误:Uncaught (in promise) TypeError: $(...).not(...).slick is not a function
    • 这告诉你 slick 没有附加到你引用的 jQuery 实例。令人惊讶的是,您在超时中没有看到这一点。可能的原因: 1. getTopLeague() 调用返回的速度比 slick 库加载的速度快 2. 您以某种方式设法导入了 2 个 jQuery 实例,其中一个没有安装 slick 库。
    • 我在 gulpfile 中加载了库
    【解决方案2】:

    我建议使用像 AxiosVue-Resource 这样的 Ajax 框架,然后在触发代码之前等待服务器响应。

    axios.get(url)
    .then( res => {
      //your code.
    })
    

    【讨论】:

      猜你喜欢
      • 2017-12-27
      • 1970-01-01
      • 2020-03-18
      • 2018-09-14
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多