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

标签 javascript dom vue.js vue-component ref

我在 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);
      });

但现在它返回未定义。

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

最佳答案

我强烈建议首先考虑这两个好的做法:

  • 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[ 之类的方式将焦点应用于第一个按钮按钮${index} ][0].focus();

    关于javascript - Vue.js - this.$refs.key 返回一个空数组或未定义而不是元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46646468/

    相关文章:

    javascript - 如何检测通过 JSON 数据引用的图像何时使用 AJAX 加载?

    javascript - 正则表达式将 URL 与正好一个文件夹深度匹配

    javascript - createContextualFragment 只是以字符串形式从字符串中吐出 html

    vue.js - 使用自定义表体实现选择 Vuetify 数据表的所有行

    vue.js - 在 Vue 中使用 Electron 事件时如何修复未定义的 __dirname?

    javascript - 如何在 jQuery 中做到这一点?

    javascript - 如何创建空的 jQuery 结果

    html - 关于继承的 CSS 性能

    包含链接的 div 的 Javascript dom 子级

    vue.js - 如何在 Nuxt Vue Composition API 中正确使用 Vuex getters?