本篇文章和大家了解一下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是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。
以上就是Vue常用的组件通信方式有哪些的简略介绍,当然详细使用上面的不同还得要大家自己使用过才领会。如果想了解更多,欢迎关注亿速云行业资讯频道哦!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。