this.$refs[("p" + index)].focus 不是函数

qli*_*liq 3 javascript vue.js vue-component vuejs2

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

这是帖子上的按钮:

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

div有关方面:

<div :ref="'p' + index"  class="post-description">
    {{post.description}}
</div>
Run Code Online (Sandbox Code Playgroud)

方法:

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

    this.$refs['p' + index].focus();
  },
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

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

我怎样才能解决这个问题?

Bou*_*him 8

经过一些调试后,我发现它this.$refs['p' + index]总是返回一个包含一个元素this.$refs.p0的数组,它也是你的元素,也返回一个数组,因此要解决这个问题,请尝试访问一个元素,例如this.$refs['p' + index][0]

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['p' + index][0].focus();
    }

  },
  mounted() {

  }

})
Run Code Online (Sandbox Code Playgroud)
<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="'p' + index" class="post-description">
      {{post.content}}
    </textarea>
    <a @click.prevent="setFocusEdit(index)" href="#">Edit Me</a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)