Vue 的 v-model 指令 绑定 HTML 的值 input 标签到 JavaScript 变量。 这使它成为构建表单的理想选择。假设您正在构建一个登录表单,您希望 使用 Axios 通过 HTTP POST 请求 。看起来是这样的:
const app = new Vue({
// `v-model` binds `email` to a text input in the template,
// and `password` to a password input.
data: () => ({ email: '', password: '' }),
methods: {
submit: async function() {
await axios.post('http://httpbin.org/post', {
email: this.email,
password: this.password
});
}
},
template: `
<div>
<input
type="text"
v-model="email"
placeholder="Email">
<input
type="password"
v-model="password"
placeholder="Password">
<button v-on:click="submit()">
Submit
</button>
</div>
`
});
计算属性 是在 Vue 中处理表单验证的一种巧妙方法。 你可以定义一个 emailError Vue 然后更新的属性 email 变化。 然后您可以禁用 提交 按钮,只要有 emailError:
const app = new Vue({
data: () => ({ email: '', password: '' }),
computed: {
emailError: function() {
if (this.email.length === 0) {
return 'Email is required';
}
if (!this.email.includes('@')) {
return 'Email must contain "@"';
}
return null;
}
},
methods: {
submit: async function() {
await axios.post('http://httpbin.org/post', {
email: this.email,
password: this.password
});
}
},
template: `
<div>
<input
type="text"
v-model="email"
placeholder="Email">
<input
type="password"
v-model="password"
placeholder="Password">
<button v-on:click="submit()" v-bind:disabled="emailError">
Submit
</button>
<div>
{{emailError}}
</div>
</div>
`
});
计算属性可以依赖于其他计算属性,因此您可以定义一个单独的 isFormValid 依赖于其他字段的计算属性的计算属性:
const app = new Vue({
data: () => ({ email: '', password: '' }),
computed: {
emailError: function() {
if (this.email.length === 0) {
return 'Email is required';
}
if (!this.email.includes('@')) {
return 'Email must contain "@"';
}
return null;
},
passwordError: function() {
if (this.password.length === 0) {
return 'Password is required';
}
return null;
},
isFormValid: function() {
return this.emailError == null && this.passwordError == null;
}
},
methods: {
submit: async function() {
await axios.post('http://httpbin.org/post', {
email: this.email,
password: this.password
});
}
},
template: `
<div>
<input
type="text"
v-model="email"
placeholder="Email">
<input
type="password"
v-model="password"
placeholder="Password">
<button v-on:click="submit()" v-bind:disabled="!isFormValid">
Submit
</button>
</div>
`
});
