使用Vue2.0单Html页面发送axios请求

因为项目需要,前端需要改用Vue框架,作为一个萌新,前后都要抓,两手都要硬,这里主要记录单页面Html发送请求,有不对的地方,还请大佬们多指教。

注意!官网上明确表示
Vue 不支持 IE8 及以下版本,因为 Vue 使用了 IE8 无法模拟的 ECMAScript 5 特性。但它支持所有兼容 ECMAScript 5 的浏览器。

引入官网在线Vue.js

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

可直接运行在单页面.html页面

<body>
<div id="app">
  <p>{{ message }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  }
})
</script>
</body>

以get请求为例,2.0版本之后有关Vue的请求方式官方更推荐使用axios,vue-resource虽然也能用,但官方貌似已经不维护鸟。

 methods: {
    dispNaiyo: function (message) { 
      	var obj = this;//单html页面请求,所以这里需要重新定义this,
     	axios.get('http://localhost/ms/balala/1').then(function(response){
      	var data = response.data.slice(10,-1);//根据需要截取JSON字符串
      	let a = JSON.parse(data);//将json字符串转换成json对象
      	obj.helloData = a;
		}).catch(function (error) { 
        console.log(error);
        
      });
   	 }
  }

完整代码

<html>
<head>
<meta charset="utf-8">
<title>VueTest</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
<div id="app">

	  <div>
	  <button v-on:click="clickMe()">巴拉拉小魔仙,点击就送</button>
	  </div>
  
	  <div v-for="(value,key) in helloData">
	    {{ key }} : {{ value }} 
	  </div>	
	  	
</div>

<script>
 var app = new Vue({
  el: '#app',
  data: {
    helloData: {}
  },
  methods: {
    clickMe: function () {
      var obj = this;
      axios.get('http://localhost/ms/balala/1').then(function(response){
      	var data = response.data.slice(10,-1);
      	let a = JSON.parse(data);
      	obj.helloData = a;
		}).catch(function (error) { 
        console.log(error); 
      });
   	 }
  }  
})
</script>

</body>
</html>

注意,如果后台没设置跨域就会存在跨域问题,解决的方式有

⑴百度
⑵百度
⑶百度
。。。

你可能感兴趣的:(vue)