vue.js实现表单
Vue.js 表单实现方法
双向数据绑定
使用v-model指令实现表单元素与Vue实例数据的双向绑定,适用于输入框、复选框、单选按钮等元素。
<template>
<input v-model="username" placeholder="用户名">
<textarea v-model="description"></textarea>
</template>
<script>
export default {
data() {
return {
username: '',
description: ''
}
}
}
</script>
表单验证
通过计算属性或watch监听器实现基础验证,或使用VeeValidate等专用验证库。
<template>
<input v-model="email" @blur="validateEmail">
<span v-if="error">{{ error }}</span>
</template>
<script>
export default {
data() {
return {
email: '',
error: ''
}
},
methods: {
validateEmail() {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
this.error = re.test(this.email) ? '' : '邮箱格式不正确';
}
}
}
</script>
表单提交
使用@submit.prevent阻止默认提交行为,通过方法处理数据。
<template>
<form @submit.prevent="handleSubmit">
<!-- 表单内容 -->
<button type="submit">提交</button>
</form>
</template>
<script>
export default {
methods: {
handleSubmit() {
if(this.validateForm()) {
// 提交逻辑
}
}
}
}
</script>
动态表单字段
通过v-for实现动态生成的表单字段,适用于需要增减表单项的场景。
<template>
<div v-for="(item, index) in items" :key="index">
<input v-model="item.value">
<button @click="removeItem(index)">删除</button>
</div>
<button @click="addItem">添加字段</button>
</template>
<script>
export default {
data() {
return {
items: [{ value: '' }]
}
},
methods: {
addItem() {
this.items.push({ value: '' });
},
removeItem(index) {
this.items.splice(index, 1);
}
}
}
</script>
表单组件封装
将表单控件封装为可复用的组件,通过v-model实现父子组件通信。
<!-- 子组件 CustomInput.vue -->
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
>
</template>
<script>
export default {
props: ['modelValue'],
emits: ['update:modelValue']
}
</script>
<!-- 父组件使用 -->
<template>
<CustomInput v-model="inputValue" />
</template>






