您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

使用 Vue 构建基本表单

时间:12-14来源:作者:点击数:

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>
  `
});
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐