vue-双向数据绑定获取表单form所有值

本文使用vue强大功能之一v-model双向数据绑定实现一键获取表单所有的值,都存在一个对象里面,使用JSON.stringify转换后直接得到ajax中就可以了

效果图如下:

具体实现代买如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            width: 100%;
            height: 100%;
            background-color: #eee;
        }
        form{
            width: 400px;
            height: 300px;
            border: 1px #000 solid;
            margin: 0 auto;
        }
        p{
            padding: 5px 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <form>
            <p>
                <label for="username">姓名:</label>
                <input type="text" v-model.number='user.username' id="username" autocomplete="off">
            </p>
            <p>
                <label for="password">密码:</label>
                <input type="text" v-model='user.password' id="password" autocomplete="off">
            </p>
            <p>
                <input type="checkbox" id="a" v-model='user.checkedNames ' value="篮球"><label for="a">篮球</label>
                <input type="checkbox" id="b" v-model='user.checkedNames ' value="足球"><label for="b">足球</label>
                <input type="checkbox" id="c" v-model='user.checkedNames ' value="排球"><label for="c">排球</label>
            </p>
            <p>
                <input type="radio" v-model='user.sex' value="男" id="sex1">
                <label for="sex2">男</label>
                <input type="radio" v-model='user.sex' value="女" id="sex2">
                <label for="sex2">女</label>
            </p>
            <p>
                <select name="" id="" v-model='user.year'>
                    <option value="">请选择</option>
                    <option value="1997">1997</option>
                    <option value="1998">1998</option>
                    <option value="1999">1999</option>
                </select>
            </p>
            <p>
                <input type="button" value="提交" @click="send">
            </p>
        </form>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            user: {
                username: '',
                password: '',
                checkedNames: [],
                sex: '男',    // 默认值在这里设置才有效
                year: '1998'  // 默认值在这里设置才有效
            } 
        },
        methods: {
            send() {
                console.log(this.user);
                alert(JSON.stringify(this.user))
            }
        }
    })
</script>
</html>
  学无止境,感兴趣的话可以体验一下下面的小程序,咱们一起交流

posted @ 2020-07-22 19:45  飘逸_winxin  阅读(7465)  评论(0编辑  收藏  举报