其他分享
首页 > 其他分享> > vue结合axios:get、post

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){})

测试接口

https://autumnfish.cn/api/joke/list
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