this.$refs[("p" + index)].focus 不是函数 [英] this.$refs[("p" + index)].focus is not a function

查看:219
本文介绍了this.$refs[("p" + index)].focus 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在点击时将 div 转换为输入框,以便可以编辑帖子(在循环内呈现).

这是帖子上的按钮:

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

div 相关:

{{post.description}}

方法:

 setFocusEdit(index) {console.log('关注', index);this.$refs['p' + index].focus();},

但我收到此错误:

未捕获的类型错误:this.$refs[("p" + index)].focus 不是函数

我该如何解决这个问题?

解决方案

经过一些调试我发现 this.$refs['p' + index] 总是返回一个包含 one 的数组item 是你的元素,this.$refs.p0 也返回一个数组,所以为了解决这个问题,尝试访问一个元素,比如 this.$refs['p' + 索引][0]

new Vue({el: '#app',数据:函数(){返回 {帖子:[{标题:帖子1",内容:内容1"},{标题:帖子2",内容:内容2"}],}},方法: {设置焦点编辑(索引){this.$refs['p' + index][0].focus();}},安装(){}})

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"><;/脚本><div id="应用程序"><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="#">编辑我</a>

I'd like to turn a div into input box on click, so that the post (which is rendered inside a loop) can be edited.

Here is the button on the post:

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

And the div concerned:

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

The method:

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

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

But I get this error:

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

How can I fix this?

解决方案

After some debugging i found that this.$refs['p' + index] returns always an array containing one item which is your element, this.$refs.p0 returns also an array, so to deal with that try to access the one element like 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() {

  }

})

<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>

这篇关于this.$refs[("p" + index)].focus 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆