案例完整代码:
- DOCTYPE html>
-
-
-
-
Document -
-
- div img{
- width: 100px;
- }
- .active{
- width: 300px;
- min-height: 200px;
- background-color: yellow;
- position: fixed;
- right: 50px;
- top: 100px;
- border: 1px solid blue;
- }
-
-
-
-
-
-
-
-
-
- //定义bus
- var bus = new Vue()
- //bus中有两个方法:
- //bus.$on() 监听
- //bus.$emit() 触发
-
-
- Vue.component("filmItem",{
- props:['mydata'],
- template:`
-
-
![]()
- {{mydata.name}}
-
-
- `,
- methods:{
- handleClick(){
- console.log(this.mydata.synopsis)
- //发布者
- bus.$emit("yiyi",this.mydata.synopsis)
- }
- }
- })
-
- Vue.component("filmDetail",{
- data(){
- return{
- info:""
- }
- },
-
- // 生命周期,组件创建完就会触发
- mounted(){
- //订阅者,监听要在发布之前就做好,不然有可能监听不到,
- bus.$on("yiyi",(data)=>{
- console.log("111",data)
- this.info=data
- })
- },
-
-
- template:`
-
- {{info}}
-
- `,
-
- })
-
- new Vue({
- el:"#box",
- data:{
- datalist:[],
- },
- methods:{
- handleAjax(){
- fetch("test.json").then(res=>res.json())
- .then(res=>{
- console.log(res.data.films)
- this.datalist=res.data.films
- })
- },
- }
- })
-
结果:
如果说是简单的兄弟之间的通信,可以用父组件进行通信,但是如果说稍微复杂一点呢,叔侄之间的通信呢,用父组件做中间人就很麻烦了;
有两种办法:
bus的原理:

首先定义bus:
var bus = new Vue()
发布者事件触发:
- //发布者
- bus.$emit("yiyi",this.mydata.synopsis)
订阅者监听到事件触发后,执行函数:
- // 生命周期,组件创建完就会触发
- mounted(){
- //订阅者,监听要在发布之前就做好,不然有可能监听不到,
- bus.$on("yiyi",(data)=>{
- console.log("111",data)
- this.info=data
- })
- },