I am trying to link my own custom buttons to a flickity carousel in a nuxt application. My parent component set the default value for the prop direction to left.
<CarouselBase class="w-screen carousel" :direction="direction">
<items/>
</CarouselBase>
data() {
return {
direction: 'left',
},
This is the code for my carousel component.
<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()
}
},
}
I have got this file vue-flickity.js in my plugins folder
import Vue from 'vue'
import Flickity from 'vue-flickity'
Vue.component('Flickity', Flickity)
I have got this error message =>
Cannot read properties of undefined (reading 'previous')
I don't know how to fix that...
The flickity template ref is not yet available in the mounted hook, as <Flickity> is rendered in the next cycle.
Await the next render cycle with the $nextTick() callback before accessing the template ref in mounted():
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()
}
},
}
Having the carousel as a component like this
<template>
<ClientOnly>
<Flickity ref="flickity">
<slot />
</Flickity>
</ClientOnly>
</template>
export default {
name: 'BaseCarousel',
}
and using it in my index with my own custom buttons
<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();
}
}
}
Calling next or previous need to reach flickity through both $refs.