其他分享
首页 > 其他分享> > 组件通讯的方式有哪些

组件通讯的方式有哪些

作者:互联网

步骤:

示例:

 在子组件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://img9.doubanio.com/view/photo/s_ratio_poster/public/p2455050536.jpg"
            title="大话西游之大圣娶亲"
            score="9.6"/>
        <movie-item 
            imgpath="https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2614949805.jpg"
            title="哈利·波特与魔法"
            score="9.0"/>
        <movie-item 
            imgpath="https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2614359276.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://img9.doubanio.com/view/photo/s_ratio_poster/public/p2614359276.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>

 

标签:通讯,哪些,default,bus,MovieItem,export,组件,emit
来源: https://www.cnblogs.com/zhanghaoqing/p/16411864.html