Vue第10话 表单输入绑定

逆流者 2020年01月04日 73次浏览

使用 v-model 对表单数据自动收集

  1. text/textarea
  2. checkbox
  3. radio
  4. select

编码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>09-表单输入绑定</title>
</head>
<body>
<div id="app-9">
    <!--submit.prevent 移除表单的默认行为(行为:表单提交后刷新页面,提交前的信息会丢失)-->
    <form @submit.prevent="handleSubmit">
        <span>用户名: </span>
        <input type="text" v-model="user.username"><br>
        <span>密码: </span>
        <input type="password" v-model="user.password"><br>
        <span>性别: </span>
        <input type="radio" id="female" value="female" v-model="user.sex">
        <label for="female">女</label>
        <input type="radio" id="male" value="male" v-model="user.sex">
        <label for="male">男</label><br>
        <span>爱好: </span>
        <input type="checkbox" id="basket" value="basketball" v-model="user.likes">
        <label for="basket">篮球</label>
        <input type="checkbox" id="foot" value="football"
               v-model="user.likes">
        <label for="foot">足球</label>
        <input type="checkbox" id="pingpang" value="pingpang"
               v-model="user.likes">
        <label for="pingpang">乒乓</label><br>
        <span>城市: </span>
        <select v-model="user.cityId">
            <option value="">未选择</option>
            <option v-for="city in allCity" :value="city.code">
                {{ city.name }}
            </option>
        </select><br>
        <span>介绍: </span>
        <textarea v-model="user.desc" rows="10"></textarea><br><br>
        <input type="submit" value="注册">
    </form>
</div>

<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#app-9',
        data: {
            user: {
                username: '',
                password: '',
                sex: 'female',
                likes: [],
                cityId: '',
                desc: '',
            },
            allCity: [{code: 'bj', name: '北京'}, {code: 'sh', name: '上海'},{code: 'gd', name: '广东'},{code: 'sz', name: '深圳'}],
        },
        methods: {
            handleSubmit (event) {
                alert(JSON.stringify(this.user))
            }
        }
    });
</script>
</body>
</html>