父组件传递一个动态数组给子组件,子组件遍历接收过来的数组中的每一个数值,并打印出最大值
时间: 2024-05-12 15:20:14 浏览: 17
父组件中传递动态数组的代码:
```
<template>
<div>
<ChildComponent :data="numbers" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
numbers: [10, 5, 20, 15, 30]
};
}
};
</script>
```
子组件中遍历数组并打印最大值的代码:
```
<template>
<div>
<p v-for="(number, index) in data" :key="index">{{ number }}</p>
<p>最大值为:{{ max }}</p>
</div>
</template>
<script>
export default {
props: {
data: {
type: Array,
required: true
}
},
data() {
return {
max: null
};
},
mounted() {
this.max = Math.max(...this.data);
}
};
</script>
```
子组件中使用了 props 来接收父组件传递的动态数组,并在 mounted 钩子函数中使用 Math.max() 方法获取数组的最大值,并将其赋值给 max 变量,然后在模板中输出最大值。
相关推荐
![html](https://img-home.csdnimg.cn/images/20210720083451.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)
![](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)