vue2点击一次生成一个子组件
时间: 2023-10-12 12:11:56 浏览: 38
要实现这个功能,你需要做以下几步:
1. 在父组件中定义一个计数器变量,用于存储子组件的个数。
2. 在父组件中定义一个方法,用于增加计数器变量的值,并将其作为 props 传递给子组件。
3. 在子组件中,接收父组件传递的计数器变量,并根据变量的值生成相应的子组件。
以下是示例代码:
父组件:
```
<template>
<div>
<button @click="addSubComponent">添加子组件</button>
<div>
<sub-component v-for="index in subComponentsCount" :key="index" />
</div>
</div>
</template>
<script>
import SubComponent from './SubComponent.vue';
export default {
components: {
SubComponent,
},
data() {
return {
subComponentsCount: 0,
};
},
methods: {
addSubComponent() {
this.subComponentsCount++;
},
},
};
</script>
```
子组件:
```
<template>
<div>子组件</div>
</template>
<script>
export default {
props: {
index: {
type: Number,
required: true,
},
},
};
</script>
```
在上面的示例中,我们在父组件中定义了一个计数器变量 `subComponentsCount`,并在点击按钮时调用 `addSubComponent` 方法来增加变量的值。在父组件的模板中,我们使用 `v-for` 指令来根据计数器变量的值生成相应的子组件。
在子组件中,我们接收父组件传递的 `index` prop,并在模板中显示子组件的内容。
通过这种方式,你可以实现点击一次生成一个子组件的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)