首页  >  问答  >  正文

VueJs 3 中的祖父组件向其祖父组件发送事件

我对 Vue 比较陌生,正在开发我的第一个项目。我正在努力创建一个包含多个子组件和孙组件的表单。我遇到了一个问题,我需要能够生成表单的多个副本。因此,我将一些数据属性上移了 1 级。目前,表单为ApplicationPage.Vue > TheApplication.Vue > PersonalInformation.Vue > BaseInput.Vue。我的问题是我需要通过 TheApplication 发出从 PersonalInformation 到 ApplicationPage 的更改。我很难弄清楚如何处理这种情况。我一直在寻找 Vue2 的解决方案,但没有找到 Vue3 的解决方案。

ApplicationPage.vue

template
      <TheApplication :petOptions="petOptions"
                      :stateOptions='stateOptions'
                      v-model="data.primary"
                      applicant="Primary"/>

script
data() {
    return {
      data: {
        primary: {
          personalInformation: {
            first_name: "",
            middle_name: "",
            last_name: "",
            date_of_birth: "",
            phone: null,
            email: "",
            pets: "",
            driver_license: null,
            driver_license_state: "",
            number_of_pets: null,
            additional_comments: ""
          },
        },
      },
    }
  },

TheApplication.Vue

<personal-information :petOptions="petOptions"
                                  :stateOptions='stateOptions'
                                  :personalInformation="modelValue.personalInformation"
                                  @updateField="UpdateField"
            />
methods: {
    UpdateField(field, value) {
      this.$emit('update:modelValue', {...this.modelValue, [field]: value})
    },

个人信息.vue

<base-input :value="personalInformation.first_name"
                  @change="onInput('personalInformation.first_name', $event.target.value)"
                  label="First Name*"
                  type="text" class=""
                  required/>
methods: {
    onInput(field, value) {
      console.log(field + " " + value)
      // this.$emit('updateField', { ...this.personalInformation, [field]: value })
      this.$emit('updateField', field, value)
    },
  }


P粉251903163P粉251903163350 天前714

全部回复(2)我来回复

  • P粉037880905

    P粉0378809052023-11-04 14:55:06

    对于任何不想链接事件发出的人,子对象上都有父对象,它也可用于发出事件。请务必在父级中注册发射,以避免控制台中出现警告。

    子项

    在此处调用直接父级的 $emit

    Child.vue

    <input @input="$parent.$emit('custom-event', e.target.value) />

    或者使用方法:

    <input @input="handleInput" />
    export default {
      methods: {
        handleInput(e) {
          this.$parent.$emit('custom-event', e.target.value)
        }
      }
    }

    父级

    由于是父级向祖先发出信号,因此请在此处声明发射。对于