父子组件之间通信的方式
- 父组件传递给子组件:通过props属性;
- 子组件传递给父组件:通过$emit触发事件;
父组件传递给子组件
父组件传递值到子组件需要通过过props来完成组件之间的通信; Props有两种常见的用法:
- 方式一:字符串数组,数组中的字符串就是attribute的名称;
- 方式二:对象类型,对象类型我们可以在指定attribute名称的同时,指定它需要传递的类型、是否是必须的、默认值等等;
Props的数组用法
App.vue如下
<template>
<show-info name="why" :age="18" :height="1.88"
address="广州市" abc="cba" class="active" />
<show-info name="kobe" :age="30" :height="1.87" />
<show-info :age="100" show-message="哈哈哈哈"/>
</template>
<script>
import ShowInfo from './ShowInfo.vue'
export default {
components: {
ShowInfo
}
}
</script>
ShowInfo.vue
<template>
<div class="infos">
<h2 :class="$attrs.class">姓名: {{ name }}</h2>
<h2>年龄: {{ age }}</h2>
<h2>身高: {{ height }}</h2>
<h2>Message: {{ showMessage }}</h2>
</div>
<div class="others" v-bind="$attrs"></div>
</template>
<script>
export default {
props: ["name","age","height"]
}
</script>
Props的对象用法 App.vue如下
<template>
<show-info name="why" :age="18" :height="1.88"
address="广州市" abc="cba" class="active" />
<show-info name="kobe" :age="30" :height="1.87" />
<show-info :age="100" show-message="哈哈哈哈"/>
</template>
<script>
import ShowInfo from './ShowInfo.vue'
export default {
components: {
ShowInfo
}
}
</script>
ShowInfo.vue
<template>
<div class="infos">
<h2 :class="$attrs.class">姓名: {{ name }}</h2>
<h2>年龄: {{ age }}</h2>
<h2>身高: {{ height }}</h2>
<h2>Message: {{ showMessage }}</h2>
</div>
<div class="others" v-bind="$attrs"></div>
</template>
<script>
export default {
props: {
name: {
type: String,
default: "我是默认name"
},
age: {
type: Number,
required: true,
default: 0
},
height: {
type: Number,
default: 2
},
friend: {
type: Object,
default() {
return { name: "james" }
}
},
hobbies: {
type: Array,
default: () => ["篮球", "rap", "唱跳"]
},
showMessage: {
type: String,
default: "我是showMessage"
}
}
}
</script>
当使用对象语法的时候,可以对传入的内容限制更多:
- 比如指定传入的attribute的类型;
- 比如指定传入的attribute是否是必传的;
- 比如指定没有传入时,attribute的默认值;
type的类型可以是
String Number Boolean Array Object Date Function Symbol