Vue传递值并提交

  1. 封装好的子组件 (MyForm.vue)
html 复制代码
<template>
  <form @submit.prevent="handleSubmit">
    <label for="name">Name:</label>
    <input type="text" v-model="formData.name" />

    <label for="email">Email:</label>
    <input type="email" v-model="formData.email" />

    <button type="submit">Submit</button>
  </form>
</template>

<script>
export default {
  props: {
    initialData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      formData: {
        name: this.initialData.name || '',
        email: this.initialData.email || ''
      }
    };
  },
  methods: {
    handleSubmit() {
      this.$emit('formSubmit', this.formData);  // 向父组件提交数据
    }
  }
};
</script>
  1. 父组件 (App.vue)
html 复制代码
<template>
  <div>
    <h1>Parent Component</h1>
    <MyForm :initialData="formData" @formSubmit="handleFormSubmit" />
  </div>
</template>

<script>
import MyForm from './components/MyForm.vue';

export default {
  components: {
    MyForm
  },
  data() {
    return {
      formData: {
        name: 'John Doe',
        email: 'john.doe@example.com'
      }
    };
  },
  methods: {
    handleFormSubmit(submittedData) {
      console.log('Form submitted with data:', submittedData);
      // 这里可以进行进一步的处理,例如发请求
    }
  }
};
</script>

解释:

  1. 子组件 (MyForm.vue)

    • 使用 props 接收从父组件传入的数据,并将这些数据与组件内部的 formData 进行绑定。
    • 通过 v-model 双向绑定输入框的值。
    • 提交表单时,触发自定义事件 formSubmit,并将 formData 数据通过 $emit 传递给父组件。
  2. 父组件 (App.vue)

    • 通过 props 传递初始表单数据给子组件。
    • 使用 @formSubmit 监听子组件提交事件,接收到提交的数据后在控制台输出或进行其他处理操作。

这样,子组件中的表单提交事件会触发父组件的处理函数,你可以在父组件中对提交的数据进行进一步的处理(如发送 API 请求)。

相关推荐
AC赳赳老秦2 分钟前
OpenClaw image-processing技能实操:批量抠图、图片尺寸调整,适配办公需求
开发语言·前端·人工智能·python·深度学习·机器学习·openclaw
We་ct9 分钟前
LeetCode 172. 阶乘后的零:从暴力到最优,拆解解题核心
开发语言·前端·javascript·算法·leetcode·typescript
军军君0110 分钟前
数字孪生监控大屏实战模板:可视化数字统计展示
前端·javascript·vue.js·typescript·echarts·数字孪生·前端大屏
此刻觐神17 分钟前
IMX6ULL开发板学习-03(Linux文件相关命令)
前端·chrome
吴声子夜歌34 分钟前
ES6——Iterator和for...of循环详解
前端·javascript·es6
小李子呢021138 分钟前
前端八股3---ref和reactive
开发语言·前端·javascript
落魄江湖行42 分钟前
基础篇三 Nuxt4 组件进阶:插槽与事件传递
前端·nuxt4
kerli42 分钟前
Compose 组件:LazyColumn 核心参数与 key/contentType 详解
android·前端
好运的阿财43 分钟前
“锟斤拷”问题——程序中用powershell执行命令出现中文乱码的解决办法
linux·前端·人工智能·机器学习·架构·编辑器·vim
踩着两条虫1 小时前
VTJ.PRO AI + 低代码实战:接入高德地图
前端·vue.js·ai编程