一、父组件如何主动获取子组件的数据html
方案1:$children数组
$children用来访问子组件实例,要知道一个组件的子组件多是不惟一的,因此它的返回值是个数组ide
定义Header、HelloWorld两个组件函数
<template> <div class="index"> <Header></Header> <HelloWorld :message="message"></HelloWorld> <button @click="goPro">跳转</button> </div> </template> mounted(){ console.log(this.$children) }
打印的是个数组,能够用foreach分别获得所须要的数据this
缺点:spa
没法肯定子组件的顺序,也不是响应式的code
方案2: $refshtm
<HelloWorld ref="hello" :message="message"></HelloWorld>
调用hellworld子组件的时候直接定义一个ref,这样就能够经过this.$refs获取所须要的数据。对象
this.$refs.hello.属性 this.$refs.hello.方法
2.子组件如何主动获取父组件中的数据blog
经过$parent
parent用来访问父组件实例,一般父组件都是惟一肯定的,跟children相似
this.$parent.属性 this.$parent.方法
父子组件通讯除了以上三种,还有props和emit。此外还有inheritAttrs和attrs
3.inheritAttrs
这是2。4新增的属性和接口。inheritAttrs属性控制子组件html属性上是否显示父组件提供的属性。
若是咱们将父组件Index中的属性desc、ketsword、message三个数据传递到子组件HelloWorld中的话,以下
父组件Index部分
<HelloWorld ref="hello" :desc="desc" :keysword="keysword" :message="message"></HelloWorld>
子组件:HelloWorld,props中只接受了message
props:{ message: String }
实际状况,咱们只须要message,那其余两个属性则会被看成普通的html元素插在子组件的根元素上
这样作会使组件预期功能变得模糊不清,这个时候,在子组件中写入,inheritAttrs:false,这些没用到的属性便会被去掉,true的话,就会显示。
props:{ message: String }, inheritAttrs:false
若是父组件没被须要的属性,跟子组件原本的属性冲突的时候
<HelloWorld ref="hello" type="text" :message="message"></HelloWorld>
子组件:helloworld
<template> <input type="number"> </template>
这个时候父组件中type="text",而子组件中type="number",而实际中最后显示的是type="text",这并非咱们想要的,因此只要设置inheritAttrs:false,type便会成为number。
那么上述这些没被用到的属性,如何被获取。这就用到了$attrs
3.$attrs
做用:能够获取到没有使用的注册属性,若是须要,咱们在这也能够往下继续传递。
就上述没有用到的desc和keysword就能经过$attrs获取到
经过$attr的这个特性能够父组件传递到子组件,免除父组件传递到子组件,再从子组件传递到孙组建的麻烦
父组件Index部分
<div class="index"> <HelloWorld ref="hello" :desc="desc" :keysword="keysword" :message="message"></HelloWorld> </div>
子组件helloworld部分
<div class="hello"> <sunzi v-bind="$attrs"></sunzi> <button @click="aa">获取父组件的数据</button> </div>
孙组建
<template>
<div class="header"> {{$attrs}} <br>
</div>
</template>
能够看出经过v-bind="$attrs"将数组传到孙组建中
除了以上,provide/inject也适用于隔代组件通讯,尤为是获取祖先组建的数据,很是方便
provide
选项应该是一个对象或返回一个对象的函数
provide:{ for:'demo' }
inject:['for']