【问题标题】:Passing method from parent component to child component in vuejsvuejs中父组件传递给子组件的方法
【发布时间】:2022-01-14 17:05:14
【问题描述】:

我想把父组件的这个方法传递给子组件,我解释一下:当我点击我的modal(子组件)上的确认按钮时,它必须发送父表单(父组件)的数据

父组件的方法:

 <b-form @submit.prevent="onSubmit">
.......
 </b-form>

async onSubmit() {
      this.errors = false;
      await this.$store.commit('commit_contractable_id', this.id)
      await this.$store.dispatch('create_contract', this.form)
    },

我的子组件按钮模态:

<button type="submit" class="btn btn-lg btn-outline-primary w-50" data-dismiss="modal">
        Confirm
</button>

我想当我点击确认时执行父组件中的功能

【问题讨论】:

  • 在子组件中发出事件,在父组件中监听,然后触发父组件onSubmit。 Here is vue docs。在您的子组件中,您可以使用v-on:click="$emit('modal-submit')",在父组件中使用v-on:modal-submit="onSubmit"。您还可以使用$emit 传递表单数据,然后在父级中获取该数据。检查文档示例

标签: javascript vue.js vuejs2


【解决方案1】:

使用Emit(根据@ljubadr 的评论)。

英文:

子组件:'嘿,父母!这件事发生了!'

父组件:'哦,真的吗?!那我就做这件事吧!'

在代码中:

子组件:

methods: {
  doSomething() {
    this.$emit('foobar'); // You can also send up a value(object)
  }

父组件:

<template>
  <child-component @foobar="doThisThing" />
</template>

<script>
...

methods: {
  doThisThing() {....
...
</script>

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 2020-09-16
    • 2020-11-23
    • 1970-01-01
    • 2021-12-27
    • 2016-03-27
    • 2019-01-07
    相关资源
    最近更新 更多