父传子的两种方式
静态属性传参
- 在不定义 props 类型的情况下 props 接受到的均为 String。
- 当 props 属性指定为 Boolean 时,并且只有属性 key 没有值 value 时接受到的是 true
动态属性传参
- 若是表达式,则获取表达式的值
```vue
子组件使用props接收
```vue
<template>
<view>
<view :class="color">{{ title }}</view>
<image :src="icon"></image>
<view>{{num}}</view>
</view>
</template>
<script>
export default {
props: {
title: {
type: [String, Number], // 类型
default: "确定" // 默认值
},
icon: {
type: [String],
default: ""
},
num: {
type: [Number],
default: "1"
}
}
}
</script>
子传父
子组件使用$emit
<script>
export default {
data() {
return {
result: '成功啦!',
}
},
methods: {
goFather() {
// 通过$emit的进行传递
// toFather:自定义父组件事件名称
// this.result:传递给父组件的值
this.$emit('toFather', this.result)
},
},
created() {
this.goTo()
},
}
</script>
父组件接收
<template>
<view>
<view>子组件的值:{{ result }}</view>
<!-- @toFather:子定义的事件名称 getResult:父定义的事件处理函数 -->
<son-1 @toFather="getResult"></son-1>
</view>
</template>
<script>
export default {
data() {
return {
result: '',
}
},
methods: {
// 此时参数为子组件传递的值
getResult(e) {
this.result = e
},
},
}
</script>