【问题标题】:How to get value from the Child component of another Parent in Vue js?如何从 Vue js 中另一个 Parent 的 Child 组件中获取价值?
【发布时间】:2018-03-09 07:47:39
【问题描述】:

我有组件 A,它有 2 个子组件 C1 和 C2。在 C1 组件中,有一个函数可以从 C2 中的相同源获取数据。 对于C1

<template>

</template>

<script>
export default {
  url = 'abc.com';
  name: 'c',
  data () {
    return {
    users:'',
  }},
  methods: {
    getData: function () {
    $.get(url, function( data ) {
        this.users = data;
        var ab = this.users.ab ;
        var pq = this.users.pq ;
        

     )};

}}
}
</script>

对于 C2

<template>

</template>

<script>
export default {
  url = 'abc.com';
  name: 'c',
  data () {
    return {
    users:'',
  }},
  methods: {
    getData: function () {
    $.get(url, function( data ) {
        this.users = data;
        var cd = this.users.cd ;
        var rs = this.users.rs ;

     )};

}}
}
</script>

AND我还有另一个组件 D

<template>

</template>

<script>
export default {
  data () {
    return {
  }},
  methods: {
    showDataABCD: function () {
    
      // here I want to access all data of users object of C1 and C2]
      // especially ab, cd


},
 showDataPQRS: function () {
    
      // here I want to access all data of users object of C1 and C2
      //especially PQ, RS


}

}

</script>

在这个 D 组件中,我需要访问这两个组件的对象。我可以使用状态或任何其他可能的方式吗?

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

有很多方法可以实现您的目标。

  • 您可以给每个子组件一个“ref=...”并直接从父组件访问它们。 (假设 A 是 D 的孩子)
  • 您可以将 http 请求的答案提交给状态
  • 您可以使用数据作为参数向上向父组件发出事件并将其存储(假设 A 是 D 的子组件)
  • 您可以使用 eventbus 将数据从孩子传递给他们的父母

但是,如果您想从组件 D 触发搜索,您可能需要首先在 C1 和 C2 上添加一个自定义事件侦听器 (eventbus.$on...)。 (你也可以传递一个回调函数)

【讨论】:

  • 不,A 是孩子 C1 和 C2 的父母
【解决方案2】:

你可以调整我在这里描述的模式Vue.js edit variables in dynamic components

只需将您想要共享的对象作为来自父级的道具传递。然后,随着子节点发出更新的数据,让父节点对其进行设置,数据将向下流向具有“共享状态”的子节点。

数据将流向父->子->子更新->父接收更新->所有子更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多