本篇文章给大家详细介绍一下vue常用的组件通信方式。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
组建通信的基本模式:父子组件的关系可以总结为 prop 向下传递,事件向上传递。父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消息
1.props(父组件向子组件传值)
parent.vue
立即学习“前端免费学习笔记(深入)”;
import child from "./child" export default { components: { "parent-child" : child },data(){ return { childName : "我是child哦" } } }
登录后复制
child.vue
child的名字叫:{{childName}}
export default { props:{ childName :{ type:String, default: "" } } }
登录后复制
2.$emit(子组件向父组件传值–局部消息订阅)
parent.vue
立即学习“前端免费学习笔记(深入)”;
import child from "./child" export default { components: { "parent-child" : child },data(){ return { childName : "我是child哦" } },methods:{ childReceive(params){ this.$message(params) } } }
登录后复制
child.vue
child的名字叫:{{childName}}
export default { props:{ childName :{ type:String, default: "" } },methods:{ childNotify(params){ this.$emit("childNotify","child的名字叫"+this.childName); } } }
登录后复制
3.bus全局消息订阅
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
child的名字叫:{{childName}}
export default { props:{ childName :{ type:String, default: "" } },methods:{ childNotify(params){ this.$emit("childNotify","child的名字叫"+this.childName); }, brotherNotity(){ this.$bus.$emit("child2","child2你好呀"); } } }
向child2打招呼
登录后复制
child2.vue
child2的名字叫:{{child2Name}}
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销毁") }) } }
登录后复制
推荐学习:vue.js教程
以上就是Vue常用的组件通信方式的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3020364.html