首页 > 代码库 > 父子间通信四 ($dispatch 和 $broadcast用法)

父子间通信四 ($dispatch 和 $broadcast用法)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>js测试父子之间通信</title>
	<script type="text/javascript" src="http://www.mamicode.com/lib/boot.js"></script>
	<style>
		.box{
			width:100%;
			max-width:640px;
			margin:40px auto;
			border:1px solid #ccc;
			padding:20px;
		}
	</style>
</head>
<body>
	<div id="app" v-cloak>
		<!-- 定义 -->
		<child :msg-data="http://www.mamicode.com/msg"></child>
	</div>
	<script>
		var tx = function(){
			// 父组件
			var child = {
				template:`
				     <div class="box" name="cs-slot">slot用法</div>
                     <div class="box">
						 <i-button @click="send()">获取数据</i-button>
    					 <i-button @click="cancel" type="primary">取消数据</i-button>
    					 <div>
                             <ul>
                                 <li v-for="item in msgData">名称:{{item.name}}---id:{{item.id}}</li>
                             </ul>
    					 </div>
                     </div>
				`,
				data:function(){
					return {
						msgData:[]
					}
				},
				events:{
                   getv:function(val){
                   	  this.msgData = val;
                   },
                   clearV:function(val){
                   	  this.msgData = [];
                   }
				},
                methods:{
                	send:function(){
                        this.$dispatch(‘getList‘,‘hellow kitty‘);//调用events父类方法
                	},
                	cancel:function(){
                  	    this.$dispatch(‘clearList‘,‘hellow kitty‘);//调用events父类方法
                	}
                }

			}
			return new Vue({
				el:‘#app‘,
				data:{
					msg:[]
				},
				events:{
				   getList:function(val){
                   	  this.msg = [{name:‘百度‘,id:‘001‘},{name:‘百威‘,id:‘002‘},{name:‘腾讯‘,id:‘003‘}];
                   	  this.$broadcast(‘getv‘,this.msg);//调用events子类方法
                   },
                   clearList:function(){
                   	  this.$broadcast(‘clearV‘,‘‘);//调用events子类方法
                   }
				},
				components:{
					child:child
				}
			})
		}()
	</script>
</body>
</html>

  技术分享

               技术分享

 

父子间通信四 ($dispatch 和 $broadcast用法)