父组件 Parent.vue
// Parent.vue
import child from './child'
export default {
components: {
child
}
}
子组件 child.vue
// child.vue
export default {
props: {
msg: String
}
}
1. 现在父组件Parent.vue要传数据到子组件的msg属性,可以这样
<!-- Parent.vue -->
<template>
<child :msg='msg from parent'>
</child>
</template>
2. 现在子组件要传数据给父组件
(1)事件冒泡
子组件中 this.$emit('name', this.msg),
然后父组件监听 this.$on('name', (msg)=>{})
或者 <div @name="(msg)=>{}"></div>
(2)使用作用域插槽slot-scope(推荐)
<!-- child.vue -->
<template>
<div>
<slot :msg="msg"></slot>
</div>
</template>
<!-- Parent.vue -->
<template>
<child>
<template slot-scope="child">
<p>{{child.msg}}</p>
</template>
</child>
</template>