vue web application
【1】axios
Next is the web application about vue
axios -------------------- powerful network request library
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
get request and post request
<body>
<input type="button" value="get请求" class="get">
<input type="button" value="post请求" class="post">
<!-- 官网提供的axios在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// get请求
// 接口1:随机笑话
// 请求地址:https://autumnfish.cn/api/joke/list
// 请求方法:get
// 请求参数:num (笑话条数,数字)
// 响应内容:随即笑话
document.querySelector(".get").onclick = function(){
axios.get("https://autumnfish.cn/api/joke/list?num=3")
.then(function(response){
console.log(response);
},function(err){
console.log(err);
})
}
// post请求
// 接口2:用户注册
// 请求地址:https://autumnfish.cn/api/user/reg
// 请求方法:post
// 请求参数:username
// 响应内容:注册成功或失败
document.querySelector(".post").onclick=function(){
axios.post("https://autumnfish.cn/api/user/reg",{username:"盐焗西兰花"})
.then(function(response){
console.log(response);
},function(err){
console.log(err);
})
}
</script>
</body>
Summarize:
◆Axios must be imported before it can be used
◆Use the get or post method to send the corresponding request
◆The callback function in the then method will be triggered when the request succeeds or fails
◆Response content or error information can be obtained through the formal parameters of the callback function
[2] Combination of axios and vue
<body>
<div id="app">
<input type="button" value="获取笑话" @click="getJoke">
<p>{
{ joke }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// get请求
// 接口:随机获取一条笑话
// 请求地址:https://autumnfish.cn/api/joke
// 请求方法:get
// 请求参数:无
// 响应内容:随即笑话
var app = new Vue({
el:"#app",
data:{
joke:"很好笑的笑话"
},
methods:{
getJoke:function(){
var that=this;
axios.get("https://autumnfish.cn/api/joke")
.then(function(response){
// console.log(response.data);
that.joke=response.data; //axios中无法直接使用this,将this保存为that,就能使用了
},function(err){
console.log(err);
})
}
}
})
</script>
</body>
Summarize:
◆this in the axios callback function has changed and cannot access the data in data
◆Save this, and use the saved this directly in the callback function
◆The biggest difference from local applications is the change of data sources