Vue框架axios get請求(類似於ajax請求)
首先介紹下,這個axios請求最明顯的地方,通過這個請求進行提交的時候頁面不會刷新
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
<script src="axios.js"></script>
</head>
<body>
<div id="myapp">
<input type="button" v-on:click="showlist" value="點我">
<ul>
<li v-for="item in stulist">
代碼:{{ item.cityCode}}
城市:{{ item.cityName}}
</li>
</ul>
</div>
</body>
<script>
new Vue({
el:'#myapp',
data:{
stulist:[]
},
methods:{
showlist:function () {
url="./hotcity.json"; 這是一個自定義的json數據文件
var self = this;
axios.get(url)
.then(function (response) {
self.stulist = response.data.data.hotCity;
console.log(response)
.catch(function (err) {
})
})
}
}
})
</script>
</html>
Vue框架axios post請求(類似於ajax請求)
這個查看數據使用get請求,但是添加數據的時候如果使用get請求的話,需要添加的數據就會暴露在url中。所以使用axios中的post請求將數據存放在請求體中
這樣用戶的數據就會很安全。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
<script src="axios.js"></script>
</head>
<body>
<div id="myapp">
<input type="text" value="username" v-model="uname">
<input type="text" value="password" v-model="passw">
<input type="button" value="提交" v-on:click="login">
</div>
<script>
new Vue({
el:'#myapp',
data: {
uname:'',
passw:''
},
methods:{
login:function () {
alert(222);
url = "hotcity.json";
axios.post(url,{
name:this.uname,
password:this.passw
},{
"headers":{"Content-Type":"application/x-www-form-urlencoded"}
}).then(function (response) {
console.log(response)
if (response.code == 1){
window.location.href = "http://www.baidu.com"
}
}).catch(function (error) {
})
}
}
})
</script>
</body>
</html>
