当前位置:首页 > VUE

vue实现form表单

2026-03-10 11:40:16VUE

Vue 实现 Form 表单

基础表单结构

在 Vue 中实现表单可以通过 v-model 实现双向数据绑定。以下是一个基础表单示例:

<template>
  <form @submit.prevent="handleSubmit">
    <label for="username">用户名:</label>
    <input type="text" id="username" v-model="form.username">

    <label for="password">密码:</label>
    <input type="password" id="password" v-model="form.password">

    <button type="submit">提交</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleSubmit() {
      console.log('提交的数据:', this.form)
    }
  }
}
</script>

表单验证

使用 Vue 的 computed 属性或第三方库(如 VeeValidate)实现表单验证。

<template>
  <form @submit.prevent="handleSubmit">
    <label for="email">邮箱:</label>
    <input type="email" id="email" v-model="form.email">
    <span v-if="!isEmailValid">请输入有效的邮箱地址</span>

    <button type="submit" :disabled="!isFormValid">提交</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        email: ''
      }
    }
  },
  computed: {
    isEmailValid() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(this.form.email)
    },
    isFormValid() {
      return this.isEmailValid
    }
  },
  methods: {
    handleSubmit() {
      if (this.isFormValid) {
        console.log('表单提交:', this.form)
      }
    }
  }
}
</script>

动态表单字段

通过 v-for 实现动态表单字段。

vue实现form表单

<template>
  <form @submit.prevent="handleSubmit">
    <div v-for="(field, index) in form.fields" :key="index">
      <label :for="field.id">{{ field.label }}:</label>
      <input 
        :type="field.type" 
        :id="field.id" 
        v-model="field.value">
    </div>
    <button type="submit">提交</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        fields: [
          { id: 'name', label: '姓名', type: 'text', value: '' },
          { id: 'age', label: '年龄', type: 'number', value: '' }
        ]
      }
    }
  },
  methods: {
    handleSubmit() {
      console.log('提交的数据:', this.form.fields)
    }
  }
}
</script>

表单组件化

将表单拆分为可复用的组件。

<template>
  <form @submit.prevent="handleSubmit">
    <form-input 
      v-model="form.name"
      label="姓名"
      type="text">
    </form-input>

    <form-input 
      v-model="form.age"
      label="年龄"
      type="number">
    </form-input>

    <button type="submit">提交</button>
  </form>
</template>

<script>
import FormInput from './FormInput.vue'

export default {
  components: { FormInput },
  data() {
    return {
      form: {
        name: '',
        age: ''
      }
    }
  },
  methods: {
    handleSubmit() {
      console.log('提交的数据:', this.form)
    }
  }
}
</script>

表单输入组件

创建一个通用的表单输入组件。

vue实现form表单

<!-- FormInput.vue -->
<template>
  <div>
    <label :for="id">{{ label }}:</label>
    <input 
      :type="type" 
      :id="id" 
      :value="value"
      @input="$emit('input', $event.target.value)">
  </div>
</template>

<script>
export default {
  props: {
    value: [String, Number],
    label: String,
    type: {
      type: String,
      default: 'text'
    },
    id: String
  }
}
</script>

表单提交与 API 集成

将表单数据通过 axios 发送到后端 API。

<template>
  <form @submit.prevent="handleSubmit">
    <label for="title">标题:</label>
    <input type="text" id="title" v-model="form.title">

    <button type="submit" :disabled="isLoading">
      {{ isLoading ? '提交中...' : '提交' }}
    </button>
  </form>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      form: {
        title: ''
      },
      isLoading: false
    }
  },
  methods: {
    async handleSubmit() {
      this.isLoading = true
      try {
        const response = await axios.post('/api/posts', this.form)
        console.log('提交成功:', response.data)
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

使用 Vuex 管理表单状态

在大型应用中,可以使用 Vuex 集中管理表单状态。

// store/modules/form.js
const state = {
  formData: {
    name: '',
    email: ''
  }
}

const mutations = {
  UPDATE_FORM_FIELD(state, { field, value }) {
    state.formData[field] = value
  }
}

const actions = {
  submitForm({ state }) {
    console.log('提交的表单数据:', state.formData)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
<template>
  <form @submit.prevent="handleSubmit">
    <label for="name">姓名:</label>
    <input 
      type="text" 
      id="name" 
      :value="$store.state.form.formData.name"
      @input="updateField('name', $event.target.value)">

    <button type="submit">提交</button>
  </form>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions('form', ['submitForm']),
    updateField(field, value) {
      this.$store.commit('form/UPDATE_FORM_FIELD', { field, value })
    },
    handleSubmit() {
      this.submitForm()
    }
  }
}
</script>

标签: 表单vue
分享给朋友:

相关文章

vue实现管道

vue实现管道

Vue 中实现管道(Pipe)功能 在 Vue 中可以通过过滤器(Filters)或计算属性(Computed Properties)实现类似管道的功能,将数据经过多个处理步骤后输出。 使用过滤器(…

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 slo…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单文…

vue轮播实现

vue轮播实现

Vue 轮播实现方法 使用第三方库(推荐) 安装 swiper 或 vue-awesome-swiper 库,快速实现功能丰富的轮播效果。 以 vue-awesome-swiper 为例: npm…

vue实现发帖

vue实现发帖

使用 Vue 实现发帖功能 前端实现 创建发帖表单组件,包含标题和内容输入框,以及提交按钮。使用 v-model 绑定表单数据。 <template> <div>…