【问题标题】:Vue js execute a child function from a parent and get dataVue js 从父级执行子函数并获取数据
【发布时间】:2017-10-14 13:50:01
【问题描述】:

我正在构建一个步骤表单,我想执行验证并从我的子组件中获取数据。

所以我有一个步骤表格,我分为容器(父)和步骤 1(子)

孩子有表单数据

我的孩子

<template>
     thre is the form fiedls
</template>
<script>
 data:()=>({
    orderform:{
      first_name:'',
      lastname:''
    }
  }),

methods:{

 submitOrder(){
  this.$validator.validateAll()
     .then(
      (res)=>{
        if(res){
           //pass this.orderform to parent component

         }   

       }
      )

  }


 }

现在在父级中

<script>
   methods:{

    gotonextStep(){
       //here execute submitOrder function in the child mcomponent
       //am stuck
       //also retrieve order form data here.


    }



    }

</script>

如何在子组件中执行函数并从父组件中获取数据。

父结构更新

<stepper>
 <v-stepper-content step="1">
         <child-1></child-1>
    <button  @click.native="gotonextStep">Continue</v-btn>
  </v-stepper-content>
  ...other stepper steps
</stepper>

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    使用ref

    <child-1 ref="child1"></child-1>
    

    然后在父级中可以调用方法或从子级获取数据:

    methods:{
      goToNextStep(){
         // call child method
         let methodResult = this.$refs.child1.someChildMethod()
         // access data properties in the child
         let childData = this.$refs.child1.someChildDataProperty
      }
    }
    

    【讨论】:

      【解决方案2】:

      儿童组件

      submitOrder(){
        var that = this;
        this.$validator.validateAll()
           .then(
            (res)=>{
              if(res){
                 //pass this.orderform to parent component
                 that.emit('childValidated',this.orderform);
      
               }   
      
             }
            )
      
        }
      

      父组件

      <child-component-name @childValidated="gotonextStep"></child-component-name>
      

      方法:{

      gotonextStep(dataFromChild){
         //here execute submitOrder function
         //am stuck
         //also retrieve order form data here.
      }
      } </script>
      

      【讨论】:

      • 我要做的是在父组件中执行子组件功能。感谢您对发射的洞察力。
      猜你喜欢
      • 2021-07-19
      • 2021-06-29
      • 2020-09-24
      • 2022-01-19
      • 2018-04-02
      • 2020-06-20
      • 2015-12-05
      • 2017-06-25
      • 2021-08-13
      相关资源
      最近更新 更多