本篇文章给大家详细介绍一下vue常用的组件通信方式。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

组建通信的基本模式:父子组件的关系可以总结为 prop 向下传递,事件向上传递。父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消息

组件通信的常用三种方式
parent.vue
立即学习“前端免费学习笔记(深入)”;
<template>
<p>
<parent-child :childName="childName"></parent-child>
</p>
</template>
<script>
import child from "./child"
export default {
components: {
"parent-child" : child
},data(){
return {
childName : "我是child哦"
}
}
}
</script>child.vue
<template>
<p id="child">
child的名字叫:{{childName}}<br>
</p>
</template>
<script>
export default {
props:{
childName :{
type:String,
default: ""
}
}
}
</script>parent.vue
立即学习“前端免费学习笔记(深入)”;
<template>
<p>
<parent-child :childName="childName" @childNotify="childReceive"></parent-child>
</p>
</template>
<script>
import child from "./child"
export default {
components: {
"parent-child" : child
},data(){
return {
childName : "我是child哦"
}
},methods:{
childReceive(params){
this.$message(params)
}
}
}
</script>child.vue
<template>
<p id="child">
child的名字叫:{{childName}}<br>
</p>
</template>
<script>
export default {
props:{
childName :{
type:String,
default: ""
}
},methods:{
childNotify(params){
this.$emit("childNotify","child的名字叫"+this.childName);
}
}
}
</script>bus.js
const install = (Vue) => {
const Bus = new Vue({
methods: {
on (event, ...args) {
this.$on(event, ...args);
},
emit (event, callback) {
this.$emit(event, callback);
},
off (event, callback) {
this.$off(event, callback);
}
}
})
Vue.prototype.$bus = Bus;
}
export default install;main.js
import Bus from "./assets/js/bus"; Vue.use(Bus);
child.vue
<template>
<p id="child">
child的名字叫:{{childName}}<br>
<el-button type="primary" @click="brotherNotity">向child2打招呼</el-button>
</p>
</template>
<script>
export default {
props:{
childName :{
type:String,
default: ""
}
},methods:{
childNotify(params){
this.$emit("childNotify","child的名字叫"+this.childName);
},
brotherNotity(){
this.$bus.$emit("child2","child2你好呀");
}
}
}
</script>child2.vue
<template>
<p id="child2">
child2的名字叫:{{child2Name}}
</p>
</template>
<script>
export default {
props:{
child2Name :{
type:String,
default: ""
}
},
created(){
this.$bus.$on("child2",function(params){
this.$message(params)
})
},
beforeDestroy() {
this.$bus.$off("child2",function(){
this.$message("child2-bus销毁")
})
}
}
</script>推荐学习:vue.js教程
以上就是Vue常用的组件通信方式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号