vue如何使用總線機制解決非父子組件傳值的情況

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>非父子組件傳值(Bus/總線、發佈訂閱模式/觀察者模式)</title>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>

	<div id="root">
		<child content="Dell"></child>
		<child content="Lee"></child>
	</div>

	<script>

		Vue.prototype.bus = new Vue()

		Vue.component('child',{
			data: function() {
				return {
					selfContent: this.content
				}
			},
			props: {
				content: String
			},
			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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章