目的:想要前后端分离,前端用vue和vue-resource请求http接口地址获取数据。
首先要安装vue-resource:
npm install vue-resource
然后在入口文件main.js中引入vue-source:
import VueResource from 'vue-resource'Vue.use(VueResource)
准备工作到这里就做完了。
用来准备测试的接口:
http://ip.tianqiapi.com/?ip=
可以查询IP的一些简单信息,支持多个IP查询,IP之间用半角逗号间隔。该接口返回IP的JSON格式的信息。
vue文件中HTML部分的代码如下,使用了ElementUI的输入框和表格:
<template> <div> <el-input v-model="input1" id="inputText"></el-input> <el-button type="primary" @click="getData()">查询IP信息</el-button> <br> <el-table :data="data1" stripe> <el-table-column prop="ip" label="IP地址" width="140"> </el-table-column> <el-table-column prop="country" label="国家" width="120"> </el-table-column> <el-table-column prop="province" label="省份"> </el-table-column> <el-table-column prop="city" label="城市"> </el-table-column> <el-table-column prop="isp" label="服务供应商"> </el-table-column> </el-table> </div></template>
js部分的代码如下:
<script> export default { name: "xuanxiang2", data(){ return { data1 : [], input:'' } }, methods:{ getData(){ var text = document.getElementById("inputText").value; var api = "http://ip.tianqiapi.com/?ip="+text;//查询IP地址 this.$http.get(api).then(function (response) { console.log(typeof response.body); if(typeof response.body == "object"){ var tmp=[]; for(var key in response.body){ //key是属性,object[key]是值 tmp.push(response.body[key]);//往数组中放值 } this.data1 = tmp; } else this.data1 = response.body; },function (err) { console.log(err); }) } }, mounted(){ // this.getData(); }, }</script>
如此即可完成一次http的请求。
this.$http.get即为发起get请求的语法,其他的还有:
get请求:
this.$http.get(URL,{ params:{ key:value, } }).then(function(success){//TODO: 成功后的操作},function(error){//TODO:失败后的操作})
POST请求:
this.$http.post(URL,{ params:{ key:value, } }).then(function(success){//TODO: 成功后的操作},function(error){//TODO:失败后的操作})
JSONP请求(跨域请求):
this.$http.jsonp(URL,{ params:{ key:value, } }).then(function(success){//TODO: 成功后的操作},function(error){//TODO:失败后的操作})