【问题标题】:passing a callback function via props to child component is undefined in child vue通过 props 向子组件传递回调函数在子 vue 中未定义
【发布时间】:2018-11-29 14:26:08
【问题描述】:

我有一个 Vue 组件,它通过 props 将回调函数传递给另一个子组件。但是,它是子级中唯一未定义的部分。

我为此创建了一个repo,以便可以查看文件。在文件 brDialog.vue 中,我将按钮传递给函数 click(),它应该可以访问在 App.vue 的 props 中传递的按钮回调,但是它在 brDialog 中未定义,而其他两件事与它一起传递存在(标签和数据)。

我将发布 brDialog 文件,并在需要时发布其他文件,但我认为链接 repo 比发布所有不同的文件更容易。我对 Vue 有点陌生,所以可能我在文档中遗漏了一些东西。

如果您运行 repo 并单击标题中的 Form Test 按钮,这就是问题所在。

brDialog.vue

<template>
  <v-container>
    <v-layout row wrap>
      <v-flex xs12>
        <v-dialog
          v-model="show"
          width="500"
          persistent
          >
          <v-card>
            <v-card-title> {{ title }} </v-card-title>
            <slot name="content"></slot>
            <v-card-actions>
              <v-btn
                v-for="button in buttons"
                :key="button.label"
                small
                @click.native="click(button)"
              >
                {{ button.label }}
              </v-btn>
              <v-btn
                v-if="showCloseButton"
                small
                @click.native="closeDialog()"
              >
                {{ closeButtonLabel }}
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
import { props } from './props.js'

export default {
  name: 'brForm',
  components: {
    brTextField: () => import('@/controls/brTextField/brTextField.vue'),
    brTextArea: () => import('@/controls/brTextArea/brTextArea.vue'),
    brSelectList: () => import('@/controls/brSelectList/brSelectList.vue')
  },
  props: props,
  data () {
    return {

    }
  },
  methods: {
    async click (button) {
      const response = await button.callback(button.data)

      if (response.close) {
        this.closeDialog()
      }
    },
    closeDialog () {
      this.$emit('close')
    }
  },
  computed: {

  }
}
</script>

<style>

</style>

也许这是我在 Vue 中使用 $emit 或其他东西时缺少的东西,但它似乎应该可以工作。有人能指出为什么回调在传递给 brDialog 后未定义吗?

【问题讨论】:

    标签: javascript vue.js callback


    【解决方案1】:

    callback 未定义,因为您使用箭头函数定义了您的 data 属性(来自您的 repo 的 App.vue)并在 this 上松开了 Vue 上下文:

    data: () => {
      return {
        testingForm: {
          //...
          dialog: {
            props: {
              buttonCallback: this.testingFormSave, //<-- here
              buttons: [
                {
                  label: 'Save',
                  data: {},
                  callback: this.testingFormSave //<-- and here
                }
              ]
            }
          }
        }
      }
    },
    

    要解决您的问题,请将data: () =&gt; {...} 更改为data () {...}

    【讨论】:

    • 美丽。感谢第二双眼睛!奇迹般有效。我想这将是一件小事。我已将您的答案标记为正确。
    猜你喜欢
    • 2021-10-04
    • 2021-10-20
    • 2020-07-26
    • 2020-08-26
    • 2020-03-14
    • 2018-08-31
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多