步骤:

示例:

在子组件MovieItem.vue中

<template>
  <div class="series-item-box">
    <div>
      <img
        :src="imgpath"
      />
    </div>
    <div class="detail">
      <div class="detail-title">{{title}}</div>
      <div class="detail-score">{{score}}</div>
    </div>
  </div>
</template>
<script>
export default {
    props:['imgpath','title','score']
};
</script>

在父组件MovieList.vue中

<template>
    <div>
        <movie-item 
            imgpath="https://www.yuucn.com/wp-content/uploads/2022/08/1660193127-25b2916b5c49db6.jpg"
            title="大话西游之大圣娶亲"
            score="9.6"/>
        <movie-item 
            imgpath="https://www.yuucn.com/wp-content/uploads/2022/08/1660193136-25b2916b5c49db6.jpg"
            title="哈利·波特与魔法"
            score="9.0"/>
        <movie-item 
            imgpath="https://www.yuucn.com/wp-content/uploads/2022/08/1660193142-25b2916b5c49db6.jpg"
            title="当幸福来敲门"
            score="9.3"/>
    </div>
</template>
<script>
import MovieItem from './MovieItem.vue'
export default {
    components:{
        MovieItem
    }
}

语法:this.$emit('event',val)

步骤:

在子组件中

<template>
  <div class="series-item-box">
    <div class="pic">
      <img
        :src="imgpath"
      />
    </div>
    <div class="detail">
      <div class="detail-title">{{title}}</div>
      <div class="detail-score">{{score}}</div>
    </div>
    <div>
        <button @click="bookTicket">购票</button>
    </div>
  </div>
</template>
<script>
export default {
    props:['imgpath','title','score'],
    methods:{
        bookTicket(){
            this.$emit('make',this.title)
        }
    }
};
</script>

在父组件中

<template>
    <div>
        <movie-item 
            imgpath="https://www.yuucn.com/wp-content/uploads/2022/08/1660193142-25b2916b5c49db6.jpg"
            title="当幸福来敲门"
            score="9.3"
            @make="getval"/>
    </div>
</template>
<script>
import MovieItem from './MovieItem.vue'
export default {
    components:{
        MovieItem
    },
    methods:{
        getval(val){
           console.log(val);
        }
    }
}
</script>

步骤:

新建 eventBus.js

import Vue from 'vue'
export default new Vue();

数据发送方

<template>
    <button @click="send">发送数据</button>
</template>
<script>
import bus from './eventBus.js'
export default {
    data(){
        return{
            msg:'故人西辞黄鹤楼'
        }
    },
    methods:{
        send(){
            bus.$emit('share',this.msg)
        }
    }
}
</script>

数据接收方

<template>
    <h2>{{fromsendMsg}}</h2>
</template>
<script>
import bus from './eventBus.js'
export default {
    data(){
        return{
            fromsendMsg:''
        }
    },
    created(){
        bus.$on('share',val=>{
            this.fromsendMsg=val;
        })
    }
}
</script>

发表回复