我正在尝试将我自己的自定义按钮链接到nuxt应用程序中的flickity carousel。我的父组件将属性direction的默认值设置为left。
<CarouselBase class="w-screen carousel" :direction="direction">
<items/>
</CarouselBase>
data() {
return {
direction: 'left',
},这是我的carousel组件的代码。
<template>
<ClientOnly>
<Flickity
ref="flickity"
:key="keyIncrementer"
class="carousel"
:class="{ 'carousel--active': active }"
:options="computedOptions"
>
<slot />
</Flickity>
</ClientOnly>
</template>
<script>
export default {
name: 'BaseCarousel',
props: {
direction: {
type: String,
default: '',
},
},
mounted() {
if (this.direction === 'right') {
this.$refs.flickity.next()
} else if (this.direction === 'left') {
this.$refs.flickity.previous()
}
},
}我在我的插件文件夹中有这个文件vue-flickity.js
import Vue from 'vue'
import Flickity from 'vue-flickity'
Vue.component('Flickity', Flickity)我收到此错误消息=>
Cannot read properties of undefined (reading 'previous')我不知道该怎么解决这个问题。
发布于 2021-10-16 06:51:38
flickity模板引用在mounted钩子中还不可用,因为<Flickity>将在下一个周期中呈现。
在mounted()中访问模板ref之前,等待$nextTick() callback的下一个呈现周期
export default {
async mounted() {
// wait until next render cycle for refs to be available
await this.$nextTick()
if (this.direction === 'right') {
this.$refs.flickity.next()
} else if (this.direction === 'left') {
this.$refs.flickity.previous()
}
},
}发布于 2021-10-16 12:18:32
将carousel作为一个组件,如下所示
<template>
<ClientOnly>
<Flickity ref="flickity">
<slot />
</Flickity>
</ClientOnly>
</template>
export default {
name: 'BaseCarousel',
}并通过我自己的自定义按钮在我的索引中使用它
<template>
<CarouselBase ref="flickityIndex">
<items for the carousel/>
</CarouselBase>
<button @click="previous">Custom Previous Button</button>
<button @click="next">Custom Next Button</button>
</template>
export default {
methods: {
next() {
this.$refs.flickityIndex.$refs.flickity.next();
},
previous() {
this.$refs.flickityIndex.$refs.flickity.previous();
}
}
}调用下一个或上一个需要通过两个$refs连接到flickity。
https://stackoverflow.com/questions/69590009
复制相似问题