父组件如何获取子组件数据,子组件如何获取父组件数据,父子组件如何传值

1、父组件如何主动获取子组件的数据

方案1:$children

$children用来访问子组件实例,要知道一个组件的子组件可能是不唯一的,所以它的返回值是个数组

定义Header、HelloWorld两个组件

<template>
  <div class="index">
    <Header></Header>
    <HelloWorld :message="message"></HelloWorld>
    <button @click="goPro">跳转</button>
  </div>
</template>
mounted(){
 console.log(this.$children)
}

打印的是个数组,可以用foreach分别得到所需要的数据

缺点:

无法确定子组件的顺序,也不是响应式的

方案2: $refs

<HelloWorld ref="hello" :message="message"></HelloWorld>

调用hellworld子组件的时候直接定义一个ref,这样就可以通过this.$refs获取所需要的数据。

this.$refs.hello.属性
this.$refs.hello.方法

2.子组件如何主动获取父组件中的数据

通过$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']
原文地址:https://www.cnblogs.com/zmyxixihaha/p/12421575.html