vue教程-请假案例(非单页面)-登录(vue+axios)

要求

页面内容

  • 用户名,必须输入,有红色 * 提示
  • 密码,必须输入,长度不能少于8位,有红色 * 提示
  • 按钮,点击按钮时,做校验。校验通过,发送 ajax 请求

请求返回数据:

成功:

{
    "code":0,
    "msg":"登录成功!"
}

失败:

{
    "code":200,
    "msg":"用户名不存在或密码错误,请重新登录!"
}

代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>登录</title>

    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>

    </head>
    <body>

    <div id="app">
        <h1>登录</h1><br>
        用户名:<input v-model="username" placeholder="请输入用户名"> <br>
        密码:<input v-model="password" placeholder="请输入密码" type="password"><br>

        <input type="button" value="登录" @click='login()'>
        <div style="color:red;">{{msg}}</div>
    </div>
    <script>
    var app = new Vue({
        el: '#app', //el是element缩写
        data:{
            username:'',
            password:'',
            msg:''

        },
        methods:{
            login:function(){
                if( this.username ===""){
                    this.msg="请输入登录名!"
                    return
                }

                if( this.password ===""){
                    this.msg="输入密码!"
                    return
                }
                this.msg=""
                console.log("username:",this.username)
                console.log("password:",this.password)

                let params = new URLSearchParams();
                params.append("username", this.username);
                params.append("password", this.password)

                axios.post('login3', 
                        params
                )
                .then(res => {
                    console.log(res);
                    location.href="index.html";
                })
                .catch(error => {
                    console.log(error);
                });


            }
        }
    })
    </script>
    </body>
</html>

原文出处:https://malaoshi.top/show_1IX2oqfIOsWW.html