问题:当子组件不能通过props直接向父组件传值,该怎么做?
方法:使用this.$emit()方法向父组件传值
this.$emit()是Vue.js实例方法,用于触发自定义事件。它可以在Vue.js组件内部调用,用于向父组件发送消息。
this.$emit()方法接受两个参数:第一个参数是事件名称,第二个参数是可选的,表示传递给事件处理程序的数据。
当你在子组件中调用this.$emit('my-event', eventData)时,父组件可以监听这个事件并定义一个事件处理程序来响应它。
子组件:
onMyChannelClick (channel, index) {
if (this.isEdit) {
// 编辑状态,执行删除频道
} else {
// 非编辑状体啊,执行切换频道
this.$emit('update-active', index)
}
}
父组件:接收update-active
<channel-edit
:my-channels="channels"
:active="active"
@userChannels="updateUserChannels"
@update-active="onUpdateActive"
/>
定义update-active
onUpdateActive (index) {
this.active = index
this.isChannelEditShow = false
}