如何实现一个自定义组件,不同组件之间如何通信?

1.如何实现一个自定义组件,不同组件之间如何通信?

组件需要注册后才可以使用,有全局注册和局部注册两种方式

在实例创建前通过

<script>
Vue.component('自定义标签名称',{
    //选项
});
var app = new Vue({
    el:'#app'
})
</script>

来注册全局组件,不必把每个组件都注册到全局,在实例中,使用components选项可以局部注册组件,注册后的组件只有在该实例作用域下有效,组件中也可以使用components选项来注册组件,使组件可以嵌套。

<script>
  var Child = {
      template:'<div>局部注册组件内容</div>'
}
 var app = new Vue({
    el:'#app',
    components:{
        'my-component':Child
}
})

</script>

组件关系可分为父子组件通信、兄弟组件通信、跨级组件通信

父子组件通信:

父组件向子组件通信,通过props传递数据

子组件向父组件传递数据时,用到自定义事件,子组件用$emit()触发事件,父组件用$on()监听子组件的事件,父组件也可以直接在子组件的自定义标签上使用v-on来监听

非父子组件通信

在Vue.js 1.x中,提供$dispatch()和$broadcast()两个方法。$dispatch()用于向上级派发事件,只要是它的父级(一级或多级以上),都可以在Vue实例的events选项内接收.$broadcast()由上级向下级广播事件。

<div id="app">
    {{message}}
    <my-component></my-component>
</div>
<script>	
    Vue.component('my-component',{
        template:'<button @click="event"></button>',
		methods:{
			event:function() {
				this.$dispatch('on-message','来自内部组件的数据');
			}
		}
	})
	var app = new Vue({
	    el:'#app',
	    data:{
		message:''
		 },
	    events:{
		'on-message':function(msg) {
		    this.message = msg;
				}
		    }
			
		})
	</script>

但在Vue.js 2.x中都废弃了(不能解决兄弟组件通信问题)

在Vue.js 2.x中,推荐使用一个空的vue实例作为中央事件总线(bus),也就是一个中介

<div id="app">
		{{message}}
		<component-a></component-a>
	</div>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	<script>
		var bus = new Vue();
		Vue.component('component-a',{
			template:'<button @click="event">传递事件</button>',
			methods:{
				event:function() {
					bus.$emit('on-message','来自组件component-a的内容')
				}
			}
		})
		var app = new Vue({
			el:'#app',
			data:{
				message:''
			},
			mounted: function() {
				var _this = this;
				bus.$on('on-message',function(msg) {
					_this.message = msg;
				})
			}
		})
	</script>

这种方法实现了任何组件间的通信,如果深入使用,可以扩展bus实例,给它添加data、computed、methods等选项,这些都是可以公用的

除了bus外,还有两种方法可以实现组件间通信,父链和子组件索引

父链

在子组件中,使用this.$parent可以直接访问该组件的父实例或组件,父组件也可以通过this.$children访问它所有的子组件

<div id="app">
		{{message}}
		<component-a></component-a>
	</div>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	<script>
		var bus = new Vue();
		Vue.component('component-a',{
			template:'<button @click="event">传递事件</button>',
			methods:{
				event:function() {
					//访问到父链后,可以做任何操作,比如直接修改数据
					this.$parent.message = "来自组件component-a的内容"
				}
			}
		})
		var app = new Vue({
			el:'#app',
			data:{
				message:''
			}
			
		})
	</script>

父子组件最好还是通过props和$emit来通信

子组件索引

ps:参考Vue.js实战

猜你喜欢

转载自blog.csdn.net/brave_haha/article/details/81000633