Vue.js - this.$refs.key 返回一个空数组或未定义而不是元素
Posted
技术标签:
【中文标题】Vue.js - this.$refs.key 返回一个空数组或未定义而不是元素【英文标题】:Vue.js - this.$refs.key returns an empty array or undefined instead of element 【发布时间】: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 你还需要这方面的帮助吗?
【参考方案1】:
我强烈建议首先考虑以下两种良好做法:
https://vuejs.github.io/eslint-plugin-vue/rules/no-use-v-if-with-v-for.html https://vuejs.github.io/eslint-plugin-vue/rules/require-v-for-key.html处理完之后,我建议将index
添加到您的v-for
并将:ref
添加到各个按钮,这样您就可以在一个函数中找到它们中的每一个。
通过ref
处理数组项在这里得到了很好的描述:this.$refs[("p" + index)].focus is not a function
您应该能够使用 this.$refs[
button$index][0].focus();
之类的方式将焦点应用于第一个按钮
【讨论】:
看起来是一个清晰简洁的答案,遗憾的是我现在无法验证建议的解决方案。 感谢您的评论。我看到了问这个问题的日期,但还是写了一个答案——去年我发现自己处于类似的情况,记得很难弄清楚。以上是关于Vue.js - this.$refs.key 返回一个空数组或未定义而不是元素的主要内容,如果未能解决你的问题,请参考以下文章
为啥 isset($this->var) 在我的 Codeigniter 模型中总是返回 false?
预渲染 vue.js 2.0 组件(类似于 vue 1 中的 this.$compile)