一、父子间通信
1、父组件 --> 子组件
父组件
<detail-base-info :goods="goods"/>
子组件
props: ["goods"]
props: {
goods: 数据类型
}
2、子组件 --> 父组件
子组件
this.$emit("自定义事件名称",要传的数据);
this.$emit('swiperImageLoad')
父组件
<home-swiper @swiperImageLoad="swiperImageLoad"/>
methods:{
swiperImageLoad() {
}
}
3、ref / $refs 这种也是父子间通信方式之一
ref 这个属性用在子组件上,它的引用就指向了子组件的实例。可以通过实例来访问组件的数据和方法。
子组件
export default {
data () {
return {
name: 'JavaScript'
}
},
methods: {
sayHello () {
console.log('hello')
}
}
}
父组件
<template>
<child ref="child"></component-a>
</template>
<script>
import child from './child.vue'
export default {
components: { child },
mounted () {
console.log(this.$refs.child.name);
this.$refs.child.sayHello();
}
}
</script>
二、兄弟组件之间传值
通过一个中转(bus)
兄弟A
this.$bus.$emit('add',this.num);
兄弟B
this.$bus.$on('add',(data)=>{
this.num=data;
})
三、还有几个没咋用过
1、$parent / $children
2、$attrs / $listeners
3、依赖注入(provide/ inject)