提问人:user22869368 提问时间:11/17/2023 最后编辑:user22869368 更新时间:11/17/2023 访问量:20
如何使用 Vue2 和 Nuxt2 将表单数据从嵌套组件传递到外部组件
How can I pass form data from a nested component to a outer component using Vue2 and Nuxt2
问:
我是相当陌生的,可以边走边看和学习。我正在尝试从内置于不同组件的表单中获取数据。流是外部组件调用内部组件调用嵌套组件。我需要将嵌套组件中的数据传递到表单提交按钮所在的外部组件,以便它可以将数据发布到 endpont。我尝试过使用 this.$emit,但就像从未读取过该方法一样,因为我在该方法中的日志没有显示。我想我已经尝试了我在堆栈溢出上找到的所有解决方案,但仍然没有成功。我尝试使用 vuex,但这似乎不是正确的解决方案,因为我没有显示到页面。任何意见都会有所帮助。我提供了代码应该是什么的框架。每个组件中的表单将有更多的字段,但现在我只使用一个字段来尝试成功传递该数据。
外部组件
<template>
<v-dialog v-model="dialog">
<v-card>
<v-card-text>
<InnerComponent
ref=source
@loadData=”updateForm”
/>
</v-card-text>
<v-card-actions>
<v-btn text @click.prevent="formSubmit">Save</v-btn>
<v-btn text @click.stop="closeDialog">Close</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script>
import InnerComponent from "sourcePath";
export default {
components: {
InnerComponent,
},
data() {
return {
dialog: false,
import: true,
source: null,
formData{}
};
},
methods: {
updateForm(formData) {
this.formData = formData;
},
formSubmit() {
try {
this.$axios
.post("endpointurl", formData)
.then((response) => {
console.log(response, "response data");
});
} catch (error) {
console.log(error);
}
},
closeDialog() {
this.dialog = false;
},
},
};
</script>
内部组件
<template>
<v-card>
<v-card-text>
<v-form ref="form">
<v-col>
<v-text-field
v-model="email"
label="email">
</v-text-field>
</v-col>
<!-- Other form fields -->
</v-form>
</v-card-text>
</v-card>
<NestedComponent
Ref=”childForm”
@grabData=”sendData”
/>
</template>
<script>
export default {
data() {
return {
email: ''”
};
},
methods: {
sendData(formData) {
this.$emit('loadData', formData); // this would be called in the outer component??
console.log(formData, "form data");
},
},
};
</script>
嵌套组件
<template>
<v-form ref="form">
<v-col>
<v-text-field
v-model="name"
label="name">
</v-text-field>
</v-col>
<!-- Other form fields -->
</v-form>
</template>
<script>
export default {
data() {
return {
name:””
};
methods: {
getFormData() {
let formData = {name: this.name}
console.log(formData, “data”);
this.$emit('form-updated', formData);
},
},
mounted(){
this.getFormData();
}, // I have this mounted but I need it to grab the data after the page loads not before. I tried adding to compuetd, but that doesnt seem right either.
};
</script>
这给了我错误,并且没有任何东西记录到控制台
答: 暂无答案
评论
.sync
update:xxx
mutations
getters