Vue.js - this.$refs.key 返回一个空数组或 undefined 而不是元素

Inc*_*ble 8 javascript dom ref vue.js vue-component

我在 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);
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

组件的 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>
  ...
Run Code Online (Sandbox Code Playgroud)

问题是 console.log(this.$refs.tcsdialbuttons) 显示一个空数组 [],长度为 0。这是为什么呢?如何访问按钮并将焦点设置在第一个上?


我还尝试将胖箭头功能更改为正常功能:

      TcsEventBus.$on('tcs-show-confirm', function() {
        console.log(this.$refs.tcsdialbuttons);
      });
Run Code Online (Sandbox Code Playgroud)

但现在它返回未定义。


我刚刚发现我不能引用组件中的任何元素,即使它在我的项目中的其他组件中工作。我不明白。。

小智 1

我强烈建议首先考虑这两个良好实践:

一旦解决了这个问题,我建议将indexv-for添加:ref 到各个按钮,这样您就可以在功能中找到它们中的每一个。

使用数组项 viaref在这里得到了很好的描述:this.$refs[("p" + index)].focus 不是一个函数

您应该能够使用诸如this.$refs[button${index}之类的东西将焦点应用到第一个按钮][0].focus();