0

每次我通过使用类似这样的路由器对象推送组件来渲染组件时,我都在努力使其正常this.$router.push('/Home/mypath');工作为索引。基本上,我将索引值传递给输入文本元素的ref ,该元素位于组件的v-for循环内,所以在mounted(),我有这样的东西

mounted() {
  this.$nextTick(() => 
  {                
      this.$refs.newInp[index].focus();          
    });
  }

但即使我传递了 1 或 2 的值,它仍然专注于第一个输入元素。当我查看控制台日志时,它会在控制台上显示此错误。 TypeError:无法读取 此行上未定义指向的属性“0”this.$refs.newInp[index].focus();

获取 v-for 中数据的示例代码

async GetContentDetails() {
     let testRes =
         await axios.get('myUrl/api', {
              params: {
                   ContentId: this.$cookie.get('OpV-ContId')
                      }
                 }).then(res => this.contentItems = res.data)
                      .then()
                      .catch(error => console.log(error));
                this.testData = testRes;
}

模板:

<div v-for="(contItem, index) in contentItems" :key="contItem.commentId">
  <textarea class="reply-commented" ref="newInp"></textarea>
  </div>

如何解决此类问题?解决方案是什么?谢谢。

4

2 回答 2

1

据我了解,您想textarea在获取一些数据后关注 a ,这表示试图在mounted方法内部关注是行不通的,因为您无法判断数据是否已被提取并且textareas 是否已经存在于 DOM 中。

因此,最好的方法是在确定数据已被获取后,在then回调内部集中注意力。

new Vue({
  el: '#app',
  
  data: {
    posts: [],
    index: 3 // Change this to focus whatever textarea you want
  },
  
  mounted () {
    this.fetchItems();
  },
  
  methods: {
    fetchItems () {
      const url = 'https://jsonplaceholder.typicode.com/posts'

      axios.get(url).then(response => {
        this.posts = response.data
        
        this.$nextTick(_ => {
          this.$refs.newInp[this.index].focus()
        })
      })
    }
  }
});
<div id="app"> 
  <div v-for="(post, index) in posts" :key="post.id">
    <textarea class="reply-commented" ref="newInp" v-text="post.body"></textarea>
  </div> 
</div>



<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

于 2019-12-30T12:36:53.097 回答
0

几天来对 DOM 行为的研究和彻底的测试和观察,了解 vue.js 如何渲染组件,当然也基于其他人在这个线程上的建议。我意识到你不能真正关注 for 循环中元素的特定索引上的创建/安装属性,特别是在这种情况下,输入文本元素,如果由于其异步行为而要在组件上绑定的数据来自服务器并且您有等到组件完全呈现。所以我至少在我的情况下找到了一个解决方案,在创建或安装的属性中使用动态观察器,并为数据属性的默认更改设置一个虚拟或重复的数据属性,目的只是为了激活观察器以专注于组件渲染后的特定元素。这是它的样子。希望这对遇到与我相同情况的人有所帮助。

created() {           
            this.GetContentDetails();
            this.$watch('commentItems2', function () {
                this.$nextTick(() => {
                    this.$refs.newRep[mapCredential.state.index2].focus();
                });
            });
        },

methods: {
 async GetComment2() {
                let testRes =
                    await axios.get('myUrl/api/GetContent/GetComments')
                        .then(this.GetReply2())
                        .catch(error => console.log(error));
                this.commentItems = testRes.data;
                this.commentItems2 = testRes.data;
            },
}
于 2020-01-03T10:38:56.443 回答