VanillaJS 到 VueJS 错误:Flickity 的错误元素:旋转木马
2019-02-01
4289
我正在尝试让 此 Flickity 示例 (CodePen) 在 VueJS 组件中运行。
HTML
<div class="carousel">
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
</div>
JS
var flkty = new Flickity('.carousel');
flkty.on( 'dragStart', function() {
console.log('dragStart');
});
我收到此错误:
bad element for Flickity: carousel
我的 不起作用 的版本:
JS data ()
import Flickity from 'flickity'
var flkty = new Flickity('.carousel')
export default {
data () {
return {
flickityOptions: {
dragThreshold: 50,
initialIndex: 1,
prevNextButtons: false,
pageDots: false,
wrapAround: false,
hash: true,
percentPosition: false
},
JS mounted ()
mounted () {
flkty.on('dragStart', function () {
this.stageDragging = true
console.log('stageDragging: ' + this.stageDragging)
})
flkty.on('dragEnd', function () {
this.stageDragging = false
console.log('stageDragging: ' + this.stageDragging)
})
如何在 VueJS 组件中使用 此 Flickity 示例 ?
3个回答
在您的
<script>
部分中,JavaScript 在模板于文档中呈现之前执行,因此如果在钩子之外调用,Flickity 将无法找到
.carousel
。 Vue 实例有一个
mounted()
生命周期钩子
,它会在其模板渲染后被调用,您应该在此处创建 Flickity 轮播:
// const flkty = new Flickity(...) // DON'T DO THIS HERE
export default {
mounted() {
this.$nextTick(() => {
const flkty = new Flickity(...)
// ...
});
}
}
此外,不要将
.carousel
类名传递给 Flickity,而是将
ref
传递给
.carousel
元素,以避免抓取文档中意外的
.carousel
元素(例如,如果您有多个组件实例)。
// template
<div ref="carousel">
// script
new Flickity(this.$refs.carousel)
tony19
2019-02-01
var app = new Vue({
el: '#app',
data() {
return {
options: {
dragThreshold: 50,
initialIndex: 1,
prevNextButtons: false,
pageDots: false,
wrapAround: false,
hash: true,
percentPosition: false,
},
itemsCount: 5,
flkty: null,
}
},
mounted: function () {
this.flkty = new Flickity(`#${this.$el.id} .carousel`);
this.flkty.on( 'dragStart', function() {
console.log('dragStart');
});
}
})
Vue.config.devtools = false;
Vue.config.productionTip = false;
* { box-sizing: border-box; }
body { font-family: sans-serif; }
.carousel {
background: #FAFAFA;
}
.carousel-cell {
width: 66%;
height: 200px;
margin-right: 10px;
background: #8C8;
border-radius: 5px;
counter-increment: carousel-cell;
}
.carousel-cell:before {
display: block;
text-align: center;
content: counter(carousel-cell);
line-height: 200px;
font-size: 80px;
color: white;
}
<link href="https://npmcdn.com/flickity@2/dist/flickity.css" rel="stylesheet"/>
<script src="https://npmcdn.com/flickity@2/dist/flickity.pkgd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="carousel">
<div v-for="item in itemsCount" class="carousel-cell">{{ item }}</div>
</div>
</div>
tao
2019-02-01
特定 Rails 案例:
错误提示是因为我在同一个
layout.html.erb
上的
Javascript/Packs
中重复了 CDN 脚本标签和 JS 代码
<%= javascript_pack_tag 'flickity' %>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
Gregdebrick
2019-04-26