JQuery 不能与 Vuejs 一起使用

新手上路,请多包涵

我正在尝试将 JQuery 插件 owl carousel 添加到使用 Vuejs 呈现的列表中。

HTML

 <h4>1. Vuejs rendered items with OWL Carousel (not working)</h4>
<div id="user" class="owl-carousel">
    <div class="item" v-for="user in users">{{ user.name }}</div>
</div>

<h4>2. Pure HTML with OWL Carousel (working)</h4>
<div class="owl-carousel">
    <div class="item">Sunny</div>
    <div class="item">Michel</div>
    <div class="item">Daneil</div>
    <div class="item">Sony</div>
</div>

JS

 var list = new Vue({
    el: '#user',
    data: {
        users: []
    },
    methods: {
        listUsers: function() {
            var users = [
            {
                id: 1,
                name: 'John'
            },
            {
                id: 2,
                name: 'Deo'
            },
            {
                id: 3,
                name: 'Anjela'
            },
            {
                id: 4,
                name: 'Samantha'
            }
            ];
            this.$set('users', users);
        },

        installOWLcarousel: function() {
            $('.owl-carousel').owlCarousel();
        }
    },
    ready: function() {
        this.listUsers();
        this.installOWLcarousel();
    }
});

您可以从以下位置找到完整代码: https ://jsfiddle.net/v18yjmuq/12/

我似乎在 Vuejs 呈现列表之前 JQuery 已经完成它的执行。如何避免这个问题?我可以在完全渲染 Vuejs for 循环项后运行 JQuery 吗?

原文由 Renjith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 424
2 个回答

当使用需要 DOM 准备就绪的 jQuery 插件时,你应该使用 Vue.nextTick

来自 vue.js 文档:

将回调延迟到下一个 DOM 更新周期后执行。更改一些数据后立即使用它以等待 DOM 更新。

在您的情况下,您应该使用 ready() 方法的以下实现:

 ready: function() {
    this.listUsers();
    Vue.nextTick(function () {
        this.installOWLcarousel();
    }.bind(this))
 }

编辑:对于 Vue 2,使用 mounted()created()

原文由 demianh 发布,翻译遵循 CC BY-SA 4.0 许可协议

像这样将 ref 属性添加到 #user 元素

<div id="user" class="owl-carousel" ref="carousel_or_anything">

然后在 Vue 组件中添加 mounted 方法:

 ...
mounted: function(){
  jQuery(this.$refs.carousel_or_anything).owlCarousel();
}
...

原文由 Cong Nguyen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题