【问题标题】:How to pass data from child to parent component in vue?如何将数据从子组件传递到vue中的父组件?
【发布时间】:2020-03-18 09:18:13
【问题描述】:

我正在使用 Vue.Js 从父级多次调用我的子组件。这意味着为所有不同的调用创建了单独的实例。数据“json”将包含所有不同实例的单独值。 现在我想从父组件的所有子组件实例中获取变量 json 中存在的数据。

[Code]
Parent component
<div v-for="(value, index) in inputs" :key="index++">
     <ChildComponent :componentcount="index" ></ChildComponent>
</div>

Child Component
<template>
    <div id="hello">
        <div>
            <v-text-field :id="'ComponentHeader_' + $attrs.componentcount" v-model="header" 
                 class="headertag" label="Child Tag" @change="createJson" outlined>
            </v-text-field>       
      </div>
    </div>
</template>

<script>
export default {
    data(){
        return{
          json:"",
  }
}
}

【问题讨论】:

标签: javascript vue.js


【解决方案1】:
You can use $emit method for this purpose.
v-on directive captures the child components events that is emitted by $emit

Child component triggers clicked event:

export default {
  methods: {
    onClickButton (event) {
      this.$emit('clicked', 'someValue')
    }
  }
}
Parent component receive clicked event:

<div>
  <child @clicked="onClickChild"></child>
</div>
export default {
  methods: {
    onClickChild (value) {
      console.log(value) // someValue
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-25
    • 2017-10-20
    • 2021-08-27
    • 2019-08-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多