简介
最近在写前端h5项目,在课余的时间总结一下Vue中通过Axios的请求,更加详细的讲解进入这个官网Axios中文说明文档。这里只是简单性的记录一下代码
代码引用
首先引用Vue.j和Axios,如下HTML代码。
注:Vue.js是通过本地引用,Axios是链接的请示
我在Vue.js中使用Axios
用户登录
placeholder="请输入密码">
登 录
重 置
Vue中的网络请在
请看app.js
const vue = new Vue({
el: '.don_login',
data: {
username: '',
password: '',
},
methods: {
login: function () { //登录
if (this.username === "" || this.username === undefined) {
$.myToast("用户名不能为空,请输入用户名!");
return
}
if (this.password === "" || this.password === undefined) {
$.myToast("密码不能为空,请输入密码!");
return
}
// if (this.password.length < 6) {
// $.myToast("密码长度不能小于6!");
// return
// }
// this.requestLogin();
window.location.href = PATH_SEARCH_HOME;
},
reset: function () { //重置
console.log("进入reset");
this.username = "";
this.password = ""
},
requestLogin: function () {
//模拟登录
axios.get("data/index.json", { //get
"username": this.username,
"password": this.password
}).then(function (res) {
console.log(res);
console.log(res.data);
//判断是否登录成功。成功就保存账号和密码
//localStorage.
var userInfo = {
"username": this.username,
"password": this.password
};
// window.localStorage.userInfo = JSON.stringify(userInfo);
$.myToast("登录成功!");
//这里需要保存返回的数据
// window.sessionStorage.setItem("user", JSON.stringify(userInfo));//保存数据
window.location.href = PATH_SEARCH_HOME;
}).catch(function (error) {
console.log(error);
})
//post
// axios.post('/user', {
// "username": this.username,
// "password": this.password
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
},
getUserInfo: function () {//获取用户信息
if (window.localStorage.userInfo) { //是否存在已经登录保存的信息
var userInfo = JSON.parse(window.localStorage.userInfo);
this.username = userInfo.username;
this.password = userInfo.password;//将信息设置到页面中
}
}
},
mounted: function () {
this.getUserInfo();
}
});
总结
这里进行记录Vue中通过Axios进行网络请求,完成需求。