【发布时间】:2018-03-20 15:56:35
【问题描述】:
我在 Vue 2 中有一个对话框窗口组件,它正在侦听事件 tcs-show-confirm(它与显示对话框的事件相同,将 show 属性设置为 true - 在父组件中):
@Prop({ default: false })
show: boolean;
@Prop()
buttons: Array<TcsDialogButton>;
mounted() {
this.$nextTick(function () {
TcsEventBus.$on('tcs-show-confirm', () => {
console.log(this.$refs.tcsdialbuttons);
});
});
}
组件的 html 在这里(页脚插槽的内容不会被另一个组件的 html 替换):
...
<slot name="footer">
<div v-if="buttons && buttons.length" ref="tcsdialbuttons" v-for="(button, index) in buttons">
<button tabindex="0" class="tcs-button tcs-dialog__button" @click="$emit('close', button.emitString)">
{{button.text}}
</button>
</div>
<div style="clear: both;"></div>
</slot>
...
问题是 console.log(this.$refs.tcsdialbuttons) 显示一个长度为 0 的空数组 []。这是为什么呢?如何访问按钮并将焦点设置在第一个按钮上?
我也试过把胖箭头功能改成普通功能:
TcsEventBus.$on('tcs-show-confirm', function() {
console.log(this.$refs.tcsdialbuttons);
});
但现在它返回 undefined。
我刚刚发现我无法引用组件中的任何元素,即使它适用于我项目中的其他组件。没看懂。。
【问题讨论】:
-
我怀疑问题出在
this变量上。尝试用传统的回调函数替换TcsEventBus回调中的粗箭头函数。 -
我试过了,现在它返回 undefined。
-
你什么时候真正发出
tcs-show-confirm事件? -
例如在另一个组件中点击“注销”时:
TcsEventBus.$emit('tcs-show-confirm', new DialogMessage(DialogMessageType.Confirm, this.onCloseDialog, 'Are you sure?')); -
@Incredible 你还需要这方面的帮助吗?
标签: javascript dom vue.js vue-component ref