Vue获取表单数据的方法

2022-03-16  本文已影响0人  洪锦一

@submit.prevent 提交阻止默认跳转
v-model.trim 去除两端空格
v-model.number 将字符串转为数值
v-model.lazy 不是立即收集,而是切换焦点后收集

<template>
  <form @submit.prevent="submit">
    <p>账号:<input type="text" v-model.trim="userinfo.username" /></p>

    <p>
      性别:
      <input
        type="radio"
        name="sex"
        id="nan"
        v-model="userinfo.sex"
        value="0"
      />
      <label for="nan">男</label>
      <input type="radio" name="sex" id="nv" v-model="userinfo.sex" value="1" />
      <label for="nv">女</label>
    </p>

    <p>年龄:<input type="number" v-model.number="userinfo.age" /></p>

    <p>
      爱好:
      <input type="checkbox" id="eat" v-model="userinfo.hobby" value="eat" />
      <label for="eat">吃饭</label>
      <input
        type="checkbox"
        id="sleep"
        v-model="userinfo.hobby"
        value="sleep"
      />
      <label for="sleep">睡觉</label>
      <input type="checkbox" id="play" v-model="userinfo.hobby" value="play" />
      <label for="play">打游戏</label>
    </p>

    <p>
      城市:
      <select v-model="userinfo.city">
        <option value="">请选择</option>
        <option value="bj">北京</option>
        <option value="sh">上海</option>
        <option value="tj">天津</option>
      </select>
    </p>

    <p>
      备注:
      <textarea v-model="userinfo.remark" cols="30" rows="3"></textarea>
    </p>

    <p>
      <input type="checkbox" v-model="userinfo.agree" id="read" />
      <label for="read">阅读协议</label>
    </p>

    <button>提交</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      userinfo: {
        username: "张三",
        sex: 0,
        age: 20,
        hobby: [],
        city: "bj",
        remark: "",
        agree: false,
      },
    };
  },
  methods: {
    submit() {
      // JSON.stringify 从一个对象中解析出字符串
      // JSON.parse() 从一个字符串中解析出JSON对象
      // console.log(this.userinfo);
      console.log(JSON.parse(JSON.stringify(this.userinfo)));
    },
  },
};
</script>

<style>
</style>
上一篇下一篇

猜你喜欢

热点阅读