Vue 3 快速重置表单内容:使用 ref 和 v-model
<template>
<div>
<form @submit.prevent="submitForm">
<label>
Name:
<input v-model="formData.name" type="text" />
</label>
<label>
Email:
<input v-model="formData.email" type="email" />
</label>
<button type="submit">Submit</button>
<button type="button" @click="resetForm">Reset</button>
</form>
</div>
</template>
<script>
import { reactive, ref } from 'vue';
export default {
setup() {
const formData = reactive({
name: '',
email: '',
});
const resetForm = () => {
formData.name = '';
formData.email = '';
};
const submitForm = () => {
// 处理表单提交逻辑
console.log(formData);
};
return {
formData,
resetForm,
submitForm,
};
},
};
</script>
<p>在上面的代码中,我们使用<code>reactive</code>函数创建了一个响应式对象<code>formData</code>,其中包含了表单的初始值。然后,我们使用<code>v-model</code>指令将表单输入元素与<code>formData</code>中的相应属性进行双向绑定。</p>
<p>在重置按钮的点击事件<code>resetForm</code>中,我们将<code>formData</code>中的属性重置为空字符串,从而实现了表单的重置。</p>
<p>在提交按钮的点击事件<code>submitForm</code>中,你可以处理表单提交的逻辑,例如发送表单数据到服务器或执行其他操作。</p>
<p>请注意,<code>reactive</code>函数是 Vue 3 中用于创建响应式对象的新函数,而不是 Vue 2 中的<code>data</code>选项。</p>
原文地址: http://www.cveoy.top/t/topic/fqcu 著作权归作者所有。请勿转载和采集!