vue技术解析二之组件通信

--------------------------动画效果-----------------------------------


<transition name="router-fade" mode="out-in">
	<router-view></router-view>
</transition>

.router-fade-enter-active, .router-fade-leave-active {
  	transition: opacity .3s;
}
.router-fade-enter, .router-fade-leave-active {
  	opacity: 0;
}


----------------------父组件给子组件传参----------------------
父组件
<no-sociaty :datas='flag'></no-sociaty>
export default{
	data(){
		return {
			flag:'00000'
		}
	}
}

子组件
<div>
	{{datas}}
</div>
export default{
	props:['datas']
}


props: {
    childMsg: {
        type: Array,
        default: [0,0,0] //这样可以指定默认的值
    }
}

方法的调用

父组件
<not-read :datas='table.data' :loadFlag='table.loadFlag' v-on:childEvent="parentMethod"></not-read>

   parentMethod(a){
      this.datas = a
  }

子组件
<p  class="more0" v-show="loadFlag" @click="$emit('childEvent',1)" >加载更多</p>

  created(){
      console.log(this.table.data);
      this.$emit('childEvent');

  }


----------------------子组件给父组件传参---------------------- 子组件 <button @click='send()'></button> export default{ methods:{ send:function(){ this.$emit('listen','11111') } } } 父组件 <v-child :listen='show()'> </v-child> export default { methods:{ show:function(data){ console.log(data) } } } ----------------------非父子组件给父组件传参---------------------- 方法1: new Vue({ el: '#app', router, render: h => h(App), data: { eventHub: new Vue() } }) 某一个组件内调用事件触发 //通过this.$root.eventHub获取此对象 //调用$emit 方法 this.$root.eventHub.$emit('YOUR_EVENT_NAME', yourData) 另一个组件内调用事件接受,当然在组件销毁时接触绑定,使用$off方法 this.$root.eventHub.$on('YOUR_EVENT_NAME', (yourData)=>{ handle(yourData) } ) 方法2: let Hub = new Vue(); //创建事件中心 组件1: <div @click="eve"></div> methods: { eve() { Hub.$emit('change','hehe'); //Hub触发事件 } } 组件2: <div></div> created() { Hub.$on('change', () => { //Hub接收事件 this.msg = 'hehe'; }); }

  

原文地址:https://www.cnblogs.com/yiyi17/p/7593291.html