$attrs 包含了父做用域中不做为prop被识别的特性绑定,当一个组件没有声明props时,这里会包含全部父做用域的绑定,vue
$listeneers 包含了父做用域中的v-on事件监听器,它能够经过v-on='$listeners'传入内部组件;app
demo:ide
parent:this
<template> <div><h1>this is test tempalte</h1> <child :msg='message' msg1='msg11' msg2='msg22' @changeMessage='changeMessage' msg4='msg44'></child> </div> </template> <script> import child from '@/components/attr/attr1' export default { name:'', components:{child}, data(){return{ message:'message info', }}, methods:{ changeMessage(msg){ alert(msg); } } } </script>
childspa
<template> <div><h2 @click='change' style='color:red'>{{$attrs}}</h2> </div> </template> <script> export default { name:'', props:['msg'], components:{'child-child':child}, data(){return{ }}, methods:{ change(){ this.$emit('changeMessage','from attr1'); }, change1(msg){ alert(msg); } } } </script>
$attrs:{ "msg1": "msg11", "msg2": "msg22", "msg4": "msg44" },除了prop以外,父元素传递的全部值,若是子元素没有prop,code
$attrs是{message:'message info',"msg1": "msg11", "msg2": "msg22", "msg4": "msg44" },$listeners传递父元素的事件,任意子元素能够经过$emit触发changeMessage事件;component
$bus,bus总线blog
就是兄弟组件之间的传值,经过一个额外的vue实例来绑定事件和数据生命周期
demo:事件
var Bus = new Vue(); //为了方便将Bus(空vue)定义在一个组件中,在实际的运用中通常会新建一Bus.js Vue.component('c1',{ //这里已全局组件为例,一样,单文件组件和局部组件也一样适用 template:'<div>{{msg}}</div>', data: () => ({ msg: 'Hello World!' }), created() { Bus.$on('setMsg', content => { this.msg = content; }); } }); Vue.component('c2',{ template: '<button @click="sendEvent">Say Hi</button>', methods: { sendEvent() { Bus.$emit('setMsg', 'Hi Vue!'); } } }); var app= new Vue({ el:'#app' })
provide/inject
父组件经过provide来提供变量,而后子子组件中经过inject来注入变量,不论子组件有多深,只要调用inject就能够注入provide中的数据,只要在父元素的生命周期中,均可以调用
demo:
<template> <div><h1>this is test tempalte</h1> <child :msg='message' msg1='msg11' msg2='msg22' @changeMessage='changeMessage' msg4='msg44'></child> </div> </template> <script> import child from '@/components/attr/attr1' export default { name:'', components:{child}, provide:{ arr:[1,2,3,4], obj:{name:'zahngsan',age:12} }, data(){return{ message:'message info', }}, methods:{ changeMessage(msg){ alert(msg); } } } </script>
子组件
<template> <div><h2 @click='change' style='color:red'>{{$attrs}}</h2> <child-child v-bind='$attrs' v-on='$listeners' @change1='change1'></child-child> </div> </template> <script> import child from '@/components/attr/attr2' export default { name:'', props:['msg'], components:{'child-child':child}, data(){return{ arr:this.arr }}, inject:['arr','obj'], mounted:function(){ console.log(this.arr,this.obj); }, methods:{ change(){ this.$emit('changeMessage','from attr1'); }, change1(msg){ alert(msg); } } } </script>
子组件inject父组件中provide中的数据,能够获取到obj和arr