如何在vue中将数据从子组件传递给父组件? [英] How to pass data from child to parent component in vue?

查看:39
本文介绍了如何在vue中将数据从子组件传递给父组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<代码>[代码]父组件<div v-for="(value, index) in input" :key="index++"><ChildComponent :componentcount="index" ></ChildComponent>

子组件<模板><div id="你好"><div><v-text-field :id="'ComponentHeader_' + $attrs.componentcount" v-model="header"class="headertag" label="Child Tag" @change="createJson" 概述></v-text-field>

</模板><脚本>导出默认{数据(){返回{json:"",}}}

解决方案

为此您可以使用 $emit 方法.v-on 指令捕获 $emit 发出的子组件事件子组件触发 clicked 事件:导出默认{方法: {onClickButton(事件){this.$emit('clicked', 'someValue')}}}父组件接收点击事件:<div><child @clicked="onClickChild"></child>

导出默认{方法: {onClickChild(值){console.log(value)//someValue}}}

I am using Vue.Js where i am calling my child component multiple times from parent. Which means there are separate instance created for all the different call. Data "json" will contain seperate value for all the different instance. Now i want to fetch data present in variable json in all the instance of child component from parent component.

[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:"",
  }
}
}

解决方案

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
    }
  }
}

这篇关于如何在vue中将数据从子组件传递给父组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆