javascript - 如何在父子com[onents使用vue3组合API绑定两个输入
问题描述
我尝试使用 composition 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,反之亦然。在组件中提交逻辑。谢谢帮助!
解决方案
您应该使用 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 和组件的更多信息