![f5aa1681cf63b74c67e1714bc6dc4687.png](https://i-blog.csdnimg.cn/blog_migrate/1c0db835d20284d575abf64fe305dc22.jpeg)
1、父传子(props)
(1)父组件
<template>
<div class="father">
<child :msg="data"></child> // 3.使用子组件
</div>
</template>
<script>
import Child from "@/components/child.vue"; // 1.引入子组件
export default {
name: "father",
data() {
return {
data: "dataFromFather"
};
},
components: {
// 2.注册子组件
Child
}
};
</script>
(2)子组件
<template>
<div>
<div>我是子组件:</div>
<div class="child">子组件接收到的内容:{{msg}}</div>
</div>
</template>
<script>
export default {
name: "Child",
props: {
//用来接父组件传来的值
msg: ""
}
};
</script>
效果图:
![55ba3eae1cb3c94dd89fc4eab96899f4.png](https://i-blog.csdnimg.cn/blog_migrate/d651aab0a9a068051b77a81309f23beb.jpeg)
2、子传父($emit)
(1)子组件
<template>
<div>
<button @click="setData">传值</button> // 1.触发事件setData
</div>
</template>
<script>
export default {
name: "Child",
data() {
return {
data: "dataFromSon"
};
},
methods: {
setData() {
this.$emit("passData", this.data); // 2.将值绑定到passData上传给父组件
}
}
};
</script>
(2)父组件
<template>
<div class="father">
<div>父组件:</div>
<div>父组件接收到的内容:{{name}}</div>
<child @passData="changeData"></child> // 1.绑定自定义事件passData
</div>
</template>
<script>
import Child from "@/components/child.vue";
export default {
name: "father",
data() {
return {
name: ""
};
},
// 注册组件
components: {
Child
},
methods: {
changeData(msg) {
// 2.获取子组件传来的值msg
this.name = msg;
}
}
};
</script>
效果图:
![e3140aab735e4d55e688fb92d4ce2901.png](https://i-blog.csdnimg.cn/blog_migrate/0158e4543605c2b3777fba5bd9575052.png)
3、非父子(bus)
(1)bus.js
import Vue from 'vue'
export default new Vue()
(2)组件1
<template>
<div class="component1">
<div>我是组件1</div>
<button @click="changeData">点击</button> // 2.触发事件changeData
</div>
</template>
<script>
import Bus from './bus.js' // 1.引入bus.js
export default {
name: 'component1',
data() {
return{
msg: 'dataFromComponent1'
}
},
methods: {
changeData(){
Bus.$emit('passData', this.msg) // 3.将值绑定到passData上传给组件2
}
},
}
</script>
(3)组件2
<template>
<div class="component2">
<div>我是组件2</div>
</div>
</template>
<script>
import Bus from './bus.js' // 1.引入bus.js
export default {
name: 'component2',
mounted() {
Bus.$on('passData', (msg)=>{ // 2.接收组件1传来的值
console.log(msg)
})
},
}
</script>
效果图(控制台打印出来的值):
![31b3d76ea6c7aec2463fb117fc8ce4f1.png](https://i-blog.csdnimg.cn/blog_migrate/7ed3aa3abdcb83a2410a4eee35162216.png)