【问题标题】:this.$refs[("p" + index)].focus is not a functionthis.$refs[("p" + index)].focus 不是函数
【发布时间】:2019-06-15 19:46:11
【问题描述】:

我想在点击时将div 变成输入框,以便可以编辑帖子(在循环内呈现)。

这是帖子上的按钮:

<a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a>

还有相关的div

<div :ref="'p' + index"  class="post-description">
    {{post.description}}
</div>

方法:

  setFocusEdit(index) {
    console.log('focusing on', index);

    this.$refs['p' + index].focus();
  },

但我收到此错误:

Uncaught TypeError: this.$refs[("p" + index)].focus is not a function

我该如何解决这个问题?

【问题讨论】:

  • 控制台中有什么? index 不是 undefined,对吧?
  • 不,在控制台打印的索引值。

标签: javascript vue.js vuejs2 vue-component v-for


【解决方案1】:

由于您使用的是v-for,因此您应该使用具有静态名称的ref 属性,例如posts,它会为您提供一个引用元素的数组

new Vue({
  el: '#app',
  data: function() {
    return {
      posts: [{
          title: "post 1",
          content: "content 1"
        },
        {
          title: "post 2",
          content: "content 2"
        }
      ],

    }
  },

  methods: {
    setFocusEdit(index) {


      this.$refs.posts[index].focus();
    }

  },
  mounted() {

  }

})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>




<div id="app">
  <div class='col-md-4 mt-3' v-for="(post, index) in posts" :key="index">
    <textarea readonly ref="posts" class="post-description">
      {{post.content}}
    </textarea>
    <a @click.prevent="setFocusEdit(index)" href="#">Edit Me</a>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2021-01-22
    • 2021-03-31
    • 2018-01-19
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多