1. 程式人生 > >vue.js(vue-resource) ---jsonp跨域

vue.js(vue-resource) ---jsonp跨域

之前的筆記說axios沒有辦法處理跨域問題,所以就引入了vue-resource。使用jsonp來解決跨域問題.

   vue-resource的基本用法:

  • get(url, [options])
  • head(url, [options])
  • delete(url, [options])
  • jsonp(url, [options])
  • post(url, [body], [options])
  • put(url, [body], [options])
  • patch(url, [body], [options])
  參考下載文件地址:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

    跨域搜尋360搜尋案例:

    程式碼:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/vue.js" ></script>
		<script type="text/javascript" src="js/vue-resource/vue-resource.js" ></script>
		<script type="text/javascript">
			window.onload = function(){
				new Vue({
					el:"#main",
					data:{},
					methods:{
						sendJSONP1:function(){
							//
							this.$http.jsonp("https://sug.so.360.cn/suggest",{
								params:{
									word:'a'
								}
							}).then(resp=>{
								console.log(resp.data.s);
							},response => {
    							console.log("傳送失敗"+response.status+","+response.statusText);
  							});
						}
					}
				});
			}
			
		</script>
	</head>
	<body>
		<div id="main">
			<button type="button" @click="sendJSONP1">向360搜尋傳送請求</button>
		</div>
	</body>
</html>

注:this.$http 在引入vue-resource.js 之後,在你建立vue例項的時候就會有$http屬性來完成vue傳送http請求的需求。具體的可以參考AIP文件。

執行結果: