组件通讯的方式有哪些
-
props传递数据
步骤:
-
-
其次,在子组件中使用v-bind指令动态绑定属性,通过插值表达式动态获取数据
-
最后,在父组件的template中调用子组件标签的使用传递数据
示例:
在子组件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
}
}
-
-
其次,在父组件引用子组件标签时使用@自定义事件=“接受子组件传递数据的方法”设置接受方法
-
最后,在父组件中使用接受方法中获取数据并使用
在子组件中
<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模块,并向外共享一个Vue的实例对象
-
在数据发送方,调用bus.$emit('事件名称',要发送的数据)方法触发自定义事件
-
在数据接收方,调用bus.$on('事件名称',事件处理函数)方法注册一个自定义事件
新建 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>

浙公网安备 33010602011771号