vue中请求数据有三种方式
a.vue-resource
b.axios
c.fetch-jsonp
vue是官方提供的插件用法如下:
(1)安装模块
npm install vue-resource --save 或者 cnpm install vue-resource --save
–save操作时为了将安装的vue-resource写入package.json文件中,要不然将项目别人的时候会出现问题;
(2)引入模块
需要再main.js中import引入文件:
import VueResource from 'vue-resource';
并且Vue.use调用一下
Vue.use(VueResource);
(3)使用
可以在组件中直接调用
this.$http.get(地址).then(function(response){}function(err){})获取数据
或使用箭头函数
this.$http.get(地址).then(response=>){}function(err){})
(4)扩展
生命周期函数中调用方法,是方法在页面加载后自动执行;方法与方法之间的调用用this.方法名 this.getdata()
完整例子:
<template>
<div >
<button @click="getdata()">请求数据</button>
<br/>
<br/>
<br/>
<ul>
<li v-for="(item,key) in list"> {{item.title}}</li>
</ul>
</div>
</template>
<script>
export default {
data(){
return{
list:[]
}
},methods:{
getdata(){
var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
this.$http.get(api).then(function(response){
console.log(response);
this.list=response.body.result;
},
function(err){
console.log(err);
})
}
},mounted(){
//方法之间的直接调用 用this
this.getdata()
}
}
</script>
<style lang="scss">
</style>