【问题标题】:How can I get json collected data from child to parent component in Vue.js?如何在 Vue.js 中获取从子组件到父组件的 json 收集数据?
【发布时间】:2022-01-17 03:19:11
【问题描述】:

我在子组件中有结果数据,但我应该把它带到主组件中。

父组件中的主组件,因此每次单击按钮时,结果都应收集到主应用程序中

 <button @click="showFinalResult">Click me</button>

这里是子组件数据,我只需要在parent中以json格式显示结果,结果为输入结果

 results: [],

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

您可以为孩子发出事件以发送数据:

Vue.component('Child', {
  template: `
    <div class="">
      
    </div>
  `,
  data() {
    return {
      results: [1,2,3]
    }
  },
  mounted() {
    this.$emit('update', this.results);
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      res: [],
      show: false
    }
  },
  methods: {
    getResult(res) {
      this.res = res
    },
    showResults() {
      this.show = !this.show
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button @click="showResults">Click me</button>
  <p v-if="show">{{ res }}</p>
  <child @update="getResult" />
</div>

【讨论】:

  • 您的代码按我的预期工作,但我需要父元素中的按钮。你能稍微修改一下你的代码吗?
  • @Davis Vue.js 开发者嘿伙计,现在请检查,我更新了我的答案
猜你喜欢
  • 2022-11-23
  • 2018-08-15
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 2020-02-04
  • 2017-06-10
  • 2020-11-20
相关资源
最近更新 更多