【发布时间】:2017-03-28 01:07:54
【问题描述】:
我目前正在尝试启动并运行一个简单的 Tabs/Tab 组件。 似乎事件处理机制中的某些内容发生了变化,因此我无法让它工作。
当前实现:
Tabs.vue
<template>
<div class="tabbed-pane">
<ul class="tab-list">
<li class="tab" v-for="tab in tabs" @click="activateTab(tab)">{{ tab.header }}</li>
</ul>
<slot></slot>
</div>
</template>
<script>
import hub from '../eventhub';
export default {
props: [],
data() {
return {
tabs: []
}
},
created() {
this.$on('tabcreated', this.registerTab)
},
methods: {
registerTab(tab) {
this.tabs.push(tab);
},
activateTab(tab) {
}
}
}
</script>
Tab.vue
<template>
<div class="tab-pane" v-show="active">
<slot></slot>
</div>
</template>
<script>
import hub from '../eventhub';
export default {
props: {
'header': String
},
data() {
return {
active: false
}
},
mounted() {
this.$emit('tabcreated', this);
}
}
</script>
eventhub.js
import Vue from 'vue';
export default new Vue();
查看
<tabs>
<tab header="Test">
First Tab
</tab>
<tab header="Test2">
Second Tab
</tab>
<tab header="Test3">
Third Tab
</tab>
</tabs>
我尝试了以下方法:
- 对
$emit使用超时来测试是否是时间问题(它是 不是) - 在
Tabs组件的根元素中使用@tabcreated
模板
如果......它会起作用
- ... 我使用建议的“eventhub”功能(替换
this.$on和this.$emit与hub.$on和hub.$emit)
但这不适合我,因为我想在同一页面上多次使用Tabs 组件,而使用“eventhub”功能则不允许这样做。
- ...我用
this.$parent.$emit
但这只是感觉很奇怪和错误。
文档指出可以在直接子组件上侦听由$emit 触发的事件
https://vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced
有人有想法吗?
【问题讨论】:
标签: javascript events event-handling vue-component vue.js