捕获子组件发出的动作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了捕获子组件发出的动作相关的知识,希望对你有一定的参考价值。
我试图对子组件发出的动作作出反应。孩子发出一个名为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>
以上是关于捕获子组件发出的动作的主要内容,如果未能解决你的问题,请参考以下文章
redux-observable 无法从发出的动作中捕获错误,错误会停止动作流