vue结合axios:get、post
作者:互联网
axios使用
导包
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Get请求
axios.get(地址?key=value&key2=values).then(function(response){},function(err){})
Post请求
axios.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})
测试接口
- get请求接口:笑话
- 请求参数:num,参数说明:笑话条数,备注:类型为数字
- 响应内容:随机笑话
https://autumnfish.cn/api/joke/list
- post请求接口:用户注册
- 请求参数:username,参数说明:用户名,备注:不能为空
- 响应内容:注册成功或者失败
https://autumnfish.cn/api/user/reg
案例
<body>
<div>
<input type="button" value="get笑话" class="get"></input>
</div>
<div>
<input type="button" value="post注册" class="post"></input>
</div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
document.querySelector(".get").onclick = function(){
axios.get("https://autumnfish.cn/api/joke/list?num=1").then(function(response){
alert(response.data.data[0]);
console.log(response);
})
}
document.querySelector(".post").onclick = function(){
axios.post("https://autumnfish.cn/api/user/reg",{username:"huyi"}).then(function(response){
alert(response.data.msg);
console.log(response);
})
}
</script>
vue结合axios
导包
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
get请求
- 一条随机笑话,响应内容:一条随机笑话
https://autumnfish.cn/api/joke
案例
<body>
<div id="Joke">
<input type="button" value="get笑话" @click="getJoke"></input>
<span>{{joke}}</span>
</div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var Joke = new Vue({
el:"#Joke",
data:{
joke:"一个笑话"
},
methods:{
getJoke:function(){
var thin=this;
axios.get("https://autumnfish.cn/api/joke").then(
function(response){
thin.joke=response.data
console.log(response)
}
)
}
}
})
</script>
标签:function,axios,get,api,joke,vue,post,response 来源: https://www.cnblogs.com/Huyi-1208/p/16389663.html