如何使用 vue 3 组合在父子组件中绑定两个输入 API

How to bind two inputs in parent and child com[onents using vue3 composition API

我尝试通过组合 api 学习 vue 3,但我一直坚持这样的事情。我有一个父页面

<template>
  <q-page class="flex flex-center bg-dark row">
    <q-input
      filled
      v-model="customerModel"
      @change="setCustomer"
      dark
    />
     <RegistartionForm />
  </q-page>
</template>

<script>
import RegistartionForm from "components/RegisterComponent.vue";
import { ref } from "vue";

export default {
  components: {
    RegistartionForm,
  },
  setup() {
    const customerModel = ref("");
    return {
      customerModel,
      onSubmit() {
        console.log(customerModel.value);
      },
    };
  },
};
</script>

我的 vue 组件:

<template>
  <q-card
    class="q-pa-md sc-logon-card bg-dark col-lg-4 col-sm-12"
    align="center"
  >
    <q-input filled v-model="customerComponentModel" dark />
    <q-btn
      type="submit"
      @click="onSubmit"
    />
  </q-card>
</template>

<script>
import { ref } from "vue";
export default {
  name: "RegistartionForm",
  props: {},
  setup(props) {
    const customerComponentModel = ref("");
    return {
      customerComponentModel,
      onSubmit() {
        console.log(customerComponentModel.value);
      },
    };
  },
};
</script>

如何绑定 customerModel 和 customerComponentModel 输入? customerModel 输入中的任何更改都必须影响 customerComponentModel,反之亦然。在组件中提交逻辑。 感谢您的帮助!

<template>
  <q-page class="flex flex-center bg-dark row">
    <q-input
      filled
      v-model="customerModel"
      @change="setCustomer"
      dark
    />
     <RegistartionForm :customerModel="customerModel"/>
  </q-page>
</template>

vue component:

<script>
import { computed } from "vue";
export default {
  name: "RegistartionForm",
  props: {customerModel: String},
  setup(props) {    
    const customerComponentModel = computed(() => {
      return props.customerModel
    })
    onSubmit = () => {
        console.log(customerComponentModel.value);
      }

    return {
      customerComponentModel,
      onSubmit      
    };
  },
};
</script>

你应该使用 v-model 指令:

<RegistartionForm v-model="customerModel"/>

在子组件中:

<template>
  <input type="text" v-model="customerComponentModel" />
</template>
<script>
import { computed } from 'vue';
export default {
  props: {
    modelValue: String,
  },
  setup(props, { emit }) {
    const customerComponentModel = computed({
      get: () => props.modelValue,
      set: (value) => emit("update:modelValue", value),
    });

    return { customerComponentModel };
  },
};

现在应该绑定 customerModel 和 customerComponentModel,customerModel 中的任何更改都应该影响 customerComponentModel,反之亦然。您可以阅读有关 v-model 和组件的更多信息 here