gpt4 book ai didi

vue.js - vuejs 在 v-for 组件中访问 ref

转载 作者:行者123 更新时间:2023-12-05 02:08:33 28 4
gpt4 key购买 nike

从 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 将是一个数组,其中包含镜像数据源的子组件。

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

关于vue.js - vuejs 在 v-for 组件中访问 ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60789025/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com