如何用vue3获取表单数据代码
时间: 2024-03-21 14:42:53 浏览: 15
在Vue3中,可以使用`v-model`指令来绑定表单元素,然后通过`ref`属性获取表单元素的值。下面是一个简单的例子:
```html
<template>
<form>
<label>
Username:
<input type="text" v-model="username" />
</label>
<label>
Password:
<input type="password" v-model="password" />
</label>
<button @click.prevent="submitForm">Submit</button>
</form>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const username = ref('');
const password = ref('');
const submitForm = () => {
console.log('Username:', username.value);
console.log('Password:', password.value);
};
return {
username,
password,
submitForm,
};
},
};
</script>
```
在上面的例子中,我们使用了`ref`来创建了`username`和`password`变量,并在模板中使用了`v-model`来绑定了输入框的值。然后,在`submitForm`方法中,我们可以通过`username.value`和`password.value`来获取表单输入的值。