vue中的非父子组件传值

 

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>非父子组件传值(BUS/总线/发布订阅模式/观察者模式)</title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="root">
			<child content="Dell"></child>
			<child content="Lee"></child>
		</div> 
		
		<script>
		Vue.prototype.bus = new Vue()    //不理解的请查看js原型对象(prototype)
		
		Vue.component('child', {
			props:{
				content:String
			},
			data:function(){
				return {
					selfContent: this.content
				}
			},
			template:"<div @click='handleClick'>{{selfContent}}</div>",
			methods:{
				handleClick:function(){
					this.bus.$emit('change',this.selfContent)
				}
			},
			mounted:function(){
				var this_ = this
				this.bus.$on('change',function(msg){
					this_.selfContent = msg
				})
			}
		})
		
		var vm = new Vue({
		  el: '#root',
		})
		</script>
	</body>
</html>

  

 

posted @ 2020-05-11 18:15  本人小白  阅读(326)  评论(0编辑  收藏  举报