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



我在 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>
  ...

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


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

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

但现在它返回未定义。


刚刚发现我无法引用组件中的任何元素,即使它适用于我项目中的其他组件。我不明白。。

我强烈建议先考虑以下 2 个良好做法:

  • 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

一旦解决了这个问题,我建议在你的v-for中添加一个index,并将:ref添加到各个按钮,这样你就可以在函数中找到它们中的每一个。

通过ref处理数组项在这里有很好的描述:this.$refs[("p" + index)].focus 不是一个函数

您应该能够使用类似 button${index} this.$refs[ 将焦点应用于第一个按钮][0].focus();

最新更新