我试图对子组件发出的动作作出反应。孩子发出一个名为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>
答案 0 :(得分:3)
您需要通过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>