案例:用户登录
1、axios库
axios是一个HTTP库,可以用来发送Http请求。
基本写法:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios({
method: "post",
url: 'https://api.luf...ord/login/',
params: {
v1: 123,
v2: 456
},
data: {
name: "代码骑士",
pwd: "123"
},
headers: {
"Content-Type":"application/json"
}
}).then(function (res){
console.log(res.data);
}).catch(function (error){
console.log(error);
})
</script>
2、案例实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style>
label {
width: 60px;
display: inline-block;
text-align: right;
margin-right: 8px;
}
</style>
</head>
<body>
<div id="app">
<input type="button" value="密码登录" @click="isSms=false"/>
<input type="button" value="短信登录" @click="isSms=true"/>
<div v-show="isSms">
<p>
<label>手机号</label>
<input type="text" placeholder="手机号" v-model="sms.mobile">
</p>
<p>
<label>验证码</label>
<input type="text" placeholder="验证码" v-model="sms.code">
</p>
</div>
<div v-show="!isSms">
<p>
<label>用户名</label>
<input type="text" placeholder="用户名" v-model="info.username">
</p>
<p>
<label>密码</label>
<input type="password" placeholder="密码" v-model="info.password">
</p>
</div>
<input type="button" value="登 录" @click="loginForm"/>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
isSms: false,
info: {
username: "",
password: ""
},
sms: {
mobile: "",
code: ""
}
},
methods: {
loginForm: function () {
//1、获取用户输入的值
let dataDict = this.isSms ? this.sms : this.info;
let url;
if (this.isSms) {
url = "https://api.luffycity.com/api/v1/auth/mobile/login/?loginWay=mobile";
} else {
url = "https://api.luffycity.com/api/v1/auth/password/login/?loginWay=password";
}
//2、向某个地址发送网络请求 axios
axios({
method: "post",
url: url,
data: dataDict,
headers: {
"Content-Type": "application/json"
}
}).then(function (res) {
if(res.data.code === -1){
alert(res.data.msg);
return;
}
}).catch(function (error) {
alert("请求异常,请重新操作。");
console.log(error);
})
}
}
})
</script>
</html>
输出