Vue 组件之间常用的通信方式

164 阅读1分钟

Vue 组件之间常用的通信方式

  • props
  • 总线 eventbus
  • vuex
  • 其他
    • $parent
    • $children
    • $root
    • $refs
    • provide/inject
  • 非 prop 特性
    • $attrs
    • $listener
	props 父->子传值 用属性
		parent
			<child :faData = '来自parent'></child>
		child
			props:{
				faData:{
					type:String,
					default:""
				}
			}	
		子->父	 用自定义事件	
		child
			this.$emit('add',good)
		parent
			<child @add='cartAdd($event)'></child>
		
事件总线

任意两个组件之间都可以进行值传递和监听

	main.js 注册 
		Vue.prototype.$bus = new Vue()
	
	parent 
		<template>
			<child1 ></child1>
			<child2 ></child2>
		<template>
		
	child1
		this.$bus.$on('event-from-child2',msg=>{
				console.log(msg)
			})
	child2
		this.$bus.$emit('event-from-child2','some msg from child2')
parent/parent / root
  • 发布订阅模式,注意:实际上事件派发和订阅的是一个人
	parent 里 child1 和child2 通信
	
		<child1></child1>
		<child2></child2>
		
		
	child1
		mounted(){
			this.$parent.$on('event-from-child2',msg=>{
				console.log(msg)
			})
		}
	
	child2
		mounted(){
			this.$parent.$emit('event-from-child2','some msg from child2')
		}
	
$children

父组件可以通过children访问子组件实现父子通信children 访问子组件实现父子通信 children 拿到的是一个子组件数组,但不能保证子元素顺序,并不一定按照name顺序返回

	parent
		<button @click='goHome'></button>
		goHome(){
			this.$children[0].eat()
		}
		
	child1
		eat(){
			console.log('马上回')
		}
	child2
attrs/attrs / listeners

包含了父作用域中不作为prop被识别(且获取)的特性绑定(class 和style 除外). 当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class 和 style 除外),并且可以通过v-bind = "$attrs" 传入内部组件——在创建高级别的组件时非常有用

	parent 
		<child foo='foo' @click='onClick'></child>
		onClick(){
			console.log("来自parent的回调函数处理")
		}
	child
		<p v-on='$listeners'>{{$attrs.foo}}</p>
		并未在props 中声明foo
		v-on='$listeners' 运行会被展开并监听(在parent里监听)
		
	child2
		
refs

获取子节点引用 | 访问普通的dom 元素

provide / inject 依赖注入可以跨层级传参

能够实现祖先和后代之间传值

	ancestor
		provide(){
			return {foo:'foo'}
		}
	descendant
		inject:['foo']
		可以起别名
		inject:{bar:{from:'foo'}}