转载自: https://www.jianshu.com/p/649929d88699
父组件给子组件传递信息
子组件通过props接收来自父组件的信息
<!--父组件-->
<template>
<div>
<h2>父组件</h2>
<br>
<Child-one :parentMessage="parentMessage"></Child-one>
</div>
</template>
<script>
import ChildOne from './ChildOne';
export default{
components: {
ChildOne,
},
data() {
return {
parentMessage: '我是来自父组件的消息',
};
},
};
</script>
<style scoped>
</style>
<!--子组件-->
<template>
<div>
<h3>我是子组件一</h3>
<span>{{parentMessage}}</span>
</div>
</template>
<script>
export default{
props: ['parentMessage'],
};
</script>
<style scoped>
</style>
子组件向父组件传递信息
子组件可以通过$emit('自定义事件名称', 数据)向父组件传递信息
<!--父组件-->
<template>
<div>
<h2>父组件</h2>
<br>
<Child-one @childEvent="parentMethod"></Child-one>
</div>
</template>
<script>
import ChildOne from './ChildOne';
export default{
components: {
ChildOne,
},
data() {
return {
parentMessage: '我是来自父组件的消息',
};
},
methods: {
parentMethod() {
alert(this.parentMessage);
},
},
};
</script>
<style scoped>
</style>
<!--子组件-->
<template>
<div>
<h3>我是子组件一</h3>
</div>
</template>
<script>
export default{
mounted() {
this.$emit('childEvent');
},
};
</script>
<style scoped>
</style>
父子组件双向绑定