我试图对发出的动作做出反应。孩子发出称为init
的事件/触发/操作。我试图在我的父组件events
地图中注册该事件。但是回调永远不会发射,这使我认为我已经为发射的动作错误注册了。
我该如何应对孩子发射的事件/触发/操作?
<template>
<flickity v-if="caseStudies && caseStudies.length > 0" id="case--studies_slider"ref="flickity" :options="flickityOptions">
<div v-for="cs in caseStudies">
{{cs.title}}
</div>
</flickity>
</template>
<script type="text/javascript">
import Flickity from 'vue-flickity'
// NOTE computed properties (caseStudies) has been removed for brevity
// but I confirm that it does load with more than 1 element in the array
export default {
components: {
'Flickity': Flickity, // Upon initialisation this should emit 'init'
},
data() {
return {
flickityOptions: {
prevNextButtons: false,
}
}
},
events: {
// This never fires!
init() {
console.log(foo)
this.$refs.flickity.on('dragStart', (ev, pointer) => {
$('#case--studies_slider').addClass('is-dragging')
})
this.$refs.flickity.on('dragEnd', (ev, pointer) => {
$('#case--studies_slider').removeClass('is-dragging')
})
}
},
mounted() {
// The below code causes a runtime error 'this.$refs.flickity' is undefined
this.$refs.flickity.on('dragStart', (ev, pointer) => {
$('#case--studies_slider').addClass('is-dragging')
})
this.$refs.flickity.on('dragEnd', (ev, pointer) => {
$('#case--studies_slider').removeClass('is-dragging')
})
}
}
</script>
您需要通过V-ON将孩子事件绑定到父母:
<template>
<flickity v-if="caseStudies && caseStudies.length > 0" id="case--
studies_slider"ref="flickity" :options="flickityOptions"
v-on:init="doSomething()">
<div v-for="cs in caseStudies">
{{cs.title}}
</div>
</flickity>
</template>
<script type="text/javascript">
import Flickity from 'vue-flickity'
export default {
components: {
'Flickity': Flickity,
},
data() {
return {
flickityOptions: {
prevNextButtons: false,
}
}
},
methods: {
doSomething() {
// this will be called when the 'init' event is triggered
}
},
}
</script>