VueJS路由相同的组件而不触发OWL Carousel

时间:2018-04-21 17:31:17

标签: javascript vue.js ecmascript-6 vuejs2 vue-router

你好

我正在面对这个问题,将VueJS渲染的图像重新评估为Carousel插件(OwlCarousel),同时加载具有不同变量的相同组件

问题是当用图像加载页面时一切正常并且轮播可以显示图像,但是当点击链接转到与其他图像相同的组件时,轮播只显示一个空框。

这是我到目前为止所做的:

<template>
    <div>
        <div id="owl-work">
            <div class="item" v-for="image in project.images" :key="image.id">
                <figure><img :src="'uploads/'+image.url" alt=""></figure>
            </div>
        </div>
        <div class="similars" v-for="similar in similars">
            <router-link :key="$route.fullPath" :to="{ name: 'project', params: { id: similar.id, project:similar }}" replace>
                <h4>{{similar.title}}</h4>
            </router-link>
        </div>
    </div>
</template>
<script>
export default {
    props: ["id"],
    computed: {
        ...mapGetters(['getProject', 'getSimilars']),
        project() {
            return this.getProject(this.id)
        },
        similars() {
            return this.getSimilars(this.id)
        }

    }
}
$("#owl-work").owlCarousel();
</script>

我的路线如下:

[
  {name: 'projects', path: '/projects', component: ProjectsScreen},
  {name: 'project', path: '/project/:id', component: ProjectScreen, props: true},
]

所以问题是如何在点击<router-link>时将“相似”的项目图像加载到轮播中,这会在相同的组件中输出结果。

PS:其他字段已更改,当摆脱旋转木马时,它可以正常运行,因此它确定了旋转木马本身的设置以及VueJS如何处理路由或类似的东西..

1 个答案:

答案 0 :(得分:1)

将owl初始化移动到生命周期挂钩,以便在路由更改时再次执行:

<script>
export default {
    props: ["id"],
    computed: {
        ...mapGetters(['getProject', 'getSimilars']),
        project() {
            return this.getProject(this.id)
        },
        similars() {
            return this.getSimilars(this.id)
        }

    },
    mounted() {
        $("#owl-work").owlCarousel();
    }
}
// Removed from here
</script>

或者,更好的是,无需从id进行访问,而是使用ref

<template>
    <div>
        <div ref="owlwork">
            <div class="item" v-for="image in project.images" :key="image.id">
                <figure><img :src="'uploads/'+image.url" alt=""></figure>
            </div>
        </div>
        <div class="similars" v-for="similar in similars">
            <router-link :key="$route.fullPath" :to="{ name: 'project', params: { id: similar.id, project:similar }}" replace>
                <h4>{{similar.title}}</h4>
            </router-link>
        </div>
    </div>
</template>
<script>
export default {
    props: ["id"],
    computed: {
        ...mapGetters(['getProject', 'getSimilars']),
        project() {
            return this.getProject(this.id)
        },
        similars() {
            return this.getSimilars(this.id)
        }

    },

    mounted() {
        $(this.$refs.owlwork).owlCarousel();
    }
}
// Removed from here
</script>