从 v-for 循环中渲染一些组件。 refs 定义如下:
:ref="'category_' + index"
这是这些 refs 在控制台中的显示方式:console.log(this.$refs)
:
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)
,我得到undefined。
任何其他定义的 ref(不称为“category_..”)工作正常。
这里似乎出了什么问题?
<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>
最佳答案
当您在 v-for
上分配 refs 时,Vue 会将所有这些 refs 拉到一个数组中。所以不需要 :ref="'category_' + index"
。
相反,您可以只执行 ref="category"
并像那样访问 ref this.$refs.category[0]
。
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]);
}
}
})
<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 将是一个数组,其中包含镜像数据源的子组件。
关于vue.js - vuejs 在 v-for 组件中访问 ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60789025/