首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >vuejs访问v-for组件中的ref

vuejs访问v-for组件中的ref
EN

Stack Overflow用户
提问于 2020-03-21 14:30:11
回答 2查看 2.7K关注 0票数 3

有一些组件从v循环中呈现。参考文献的定义如下::ref="'category_' + index"这是这些参考文献如何在控制台中显示在:console.log(this.$refs)

代码语言:javascript
运行
复制
category_0: [VueComponent]
category_1: [VueComponent]
category_2: [VueComponent]
category_3: [VueComponent]
category_4: [VueComponent]
category_5: [VueComponent]
category_6: [VueComponent]
category_7: [VueComponent]
category_8: [VueComponent]
__proto__: Object

如果我尝试这样访问:console.log(this.$refs.category_0),我会得到未定义的。任何其他定义的参考文献(不称为‘category_.’)工作得很完美。

这里好像出什么问题了?

代码语言:javascript
运行
复制
<el-form-item v-for="(category,index) in Object.Products" :key="index" 
  :label="category.Name">

    <Select-product v-model="category.IdSelected" :ref="'category'" 
      ProductCategory='Ingredient' @return="handleSelectIngredient"/> 

</el-form-item>
EN

回答 2

Stack Overflow用户

发布于 2020-03-21 14:51:48

当您在一个v-for上指定refs时,Vue将在一个数组中提取所有这些引用。因此,不需要:ref="'category_' + index"

相反,您只需执行ref="category"并像this.$refs.category[0]那样访问ref。

代码语言:javascript
运行
复制
Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    arr: [1, 2, 3, 4, 5]
  },
  methods: {
    test() {
      console.log(this.$refs.category);
      console.log(this.$refs.category[0]);
    }
  }
})
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="nbr in arr" ref="category">
    {{ nbr }}
  </div>
  <button @click="test">
    test
  </button>
</div>

当ref与v-for一起使用时,您得到的ref将是一个数组,其中包含镜像数据源的子组件。

https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

票数 3
EN

Stack Overflow用户

发布于 2020-03-22 23:02:27

这就是问题所在(麦贝,它会帮助其他人):

ref类别(console.log(this.$refs.category))的调用得到了undefined,因为组件当时不可用,所以它稍后在DOM中呈现(毫秒问题)。因此,$nextTick()完成了这项工作。

代码语言:javascript
运行
复制
    async handleSelectModelAutomat(item) {
      var response         = await this.post("info/get", {IdModel: item}); 
      this.Object.Products = response.Result; 

      await this.$nextTick() 
      console.log(this.$refs.category_0) }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60789025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档