我正在尝试将 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 许可协议
当使用需要 DOM 准备就绪的 jQuery 插件时,你应该使用 Vue.nextTick 。
来自 vue.js 文档:
在您的情况下,您应该使用 ready() 方法的以下实现:
编辑:对于 Vue 2,使用
mounted()
或created()