在v-for动态创建中,如何获取指定元素下的子元素的值
时间: 2023-07-16 08:16:38 浏览: 46
在 Vue.js 中,你可以使用 `$refs` 属性来获取指定元素下的子元素的值。具体步骤如下:
1. 在子元素中给需要获取值的元素添加 `ref` 属性,如下示例:
```
<template>
<div>
<input type="text" ref="inputValue" />
</div>
</template>
```
2. 在父组件中使用 `v-for` 动态创建子元素,并给每个子元素添加 `ref` 属性,如下示例:
```
<template>
<div>
<div v-for="(item, index) in list" :key="index" ref="itemRefs">
<child-component ref="childRefs"></child-component>
</div>
</div>
</template>
```
3. 在父组件中使用 `$refs` 属性获取指定元素下的子元素的值,如下示例:
```
<script>
export default {
data() {
return {
list: [1, 2, 3]
};
},
methods: {
getValue() {
const itemRefs = this.$refs.itemRefs;
const childRefs = this.$refs.childRefs;
const inputValue = itemRefs[0].$refs.inputValue.value;
console.log(inputValue);
}
}
};
</script>
```
在上面的示例中,我们通过 `$refs` 属性获取了第一个子元素下的 `input` 元素的值,并打印输出。