# 01.props-形参
[toc]{type: "ol", level: [3,4]}
### 组件通信原则
- 不要在子组件中直接修改父组件的数据
- 数据和处理数据的函数应该在同一组件内
- 子组件修改父组件的数据,要调用父组件中用于处理数据的函数
### 组件通信方式
- props
> 父组件 --> 子组件
- 自定义事件
> 子组件 --> 父组件
- 消息订阅与发布
> 非父子组件
- vuex
> 常用数据
### 创建子组件
- 子组件
> 可以是**局部组件**{style="color:brown"}|**全局组件**{style="color:goldenrod"}
#### html结构
> 子组件内容
```html
<template id="box">
<div>
<h3>{{ brand }}</h3>
<ul>
<li v-for="item in colleges">{{ item }}</li>
</ul>
</div>
</template>
```
#### 设置位置形参
```js
const Box = {
props: ['brand', 'colleges'],
template: `#box`,
};
```
#### 控制形参类型
```js
const Box = {
props: {
brand: String,
colleges: Array,
},
template: `#box`,
};
```
#### 指定必须传入
```js
const Box = {
props: {
brand: {type: String, required:true},
colleges: {type: Array, required: false},
},
template: `#box`,
};
```
#### 定义默认数据
```js
const Box = {
props: {
brand: {type: String, required:true, default: 'Fruit'},
colleges: {type: Array, required: false, default: ['Apple', 'Banana']},
},
template: `#box`,
};
```
### 创建父组件
- 父组件
> 可以是**局部组件**{style="color:brown"}|**全局组件**{style="color:goldenrod"}|**实例**{style="color:green"}
```js
// 父组件 实例
const app = Vue.createApp({
data() {
return {
msg1: 'Fruit',
msg2: ['Pear', 'Banana', 'Orange']
}
},
// 注册子组件
components: {
'app-box': Box
}
}).mount('#app');
```
### 调用子组件
- 传递实参
> 动态绑定
> 将父组件中的数据,传递到子组件的形参中
```html
<div id="app">
<app-box :brand="msg1" :colleges="msg2"></app-box>
</div>
```
![01](imgs/01.png)