vue给form表单赋值
时间: 2023-07-03 11:04:12 浏览: 45
在 Vue 中,可以使用 `v-model` 指令来绑定表单元素和组件中的数据。当需要给表单元素赋值时,只需要将相应的数据赋值给组件中的数据即可。下面是一个简单的例子:
```html
<template>
<form>
<label>
Name:
<input type="text" v-model="name">
</label>
<label>
Age:
<input type="number" v-model="age">
</label>
<button @click="submitForm">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
name: '',
age: null
}
},
methods: {
submitForm() {
console.log(this.name, this.age);
}
},
mounted() {
// 模拟从服务器获取表单数据
const formData = {
name: 'John',
age: 25
};
// 将表单数据赋值给组件中的数据
this.name = formData.name;
this.age = formData.age;
}
}
</script>
```
在上面的例子中,我们使用 `v-model` 来绑定表单元素和组件中的数据。在组件挂载后,我们模拟从服务器获取表单数据,并将表单数据赋值给组件中的数据。这样,表单元素就被自动赋值了。