首页 > 其他 > 详细

10.请求数据

时间:2019-10-13 10:02:39      阅读:65      评论:0      收藏:0      [点我收藏+]

在vue中,有三种常用的数据请求方式:

/*
三种数据请求方式
vue-resource
axios
fetch-jsonp
*/

1.vue-resource

1.安装vue-resource

技术分享图片

 

 

cnpm install vue-resource --save

2.在src/main.js中引用

import VueResource from ‘vue-resource‘;
Vue.use(VueResource)

技术分享图片

 

 3.在组件中使用home.vue

<template>
    <div>
        <h2>这是一个首页组件</h2>
        <button @click="getData()">请求数据</button>
        <hr>
        <br>
        <ul>
          <li v-for="(item,index) in list" :key="index">{{item.title}}</li>
        </ul>
    </div>
</template>
<script>
/*
三种数据请求方式
vue-resource
axios
fetch-jsonp
*/
export default {
  name: home,  
  data () {
    return {
        msg:首页组件,
        list:[]
    }
  },
  methods:{
    getData(){
      // 请求数据
      var api=http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1
      var _self=this
      this.$http.get(api).then(
        function (response) {
          console.log(response)
          _self.list=response.data.result
        },
        function(err){
          console.log(err)
        }
      )
    }
  },
  components:{
  }

}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>

 

技术分享图片

 

 

2.axios

1.安装axios

cnpm install axios --save

技术分享图片

 

 2.在组件中引入

使用箭头函数,不用担心this的指向

<template>
    <div>
        <h2>这是一个首页组件</h2>
        <button @click="getData()">请求数据</button>
        <hr>
        <br>
        <ul>
          <li v-for="(item,index) in list" :key="index">{{item.title}}</li>
        </ul>
    </div>
</template>
<script>
import Axios from axios;
export default {
  name: home,  
  data () {
    return {
        msg:首页组件,
        list:[]
    }
  },
  methods:{
    getData(){
      // 请求数据
      var api=http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1
      Axios.get(api).then((response)=>{console.log(response);this.list=response.data.result}).catch((err)=>{console.log(err)})
    }
  },
  components:{
  }

}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>

 

技术分享图片

 

 3.fetch-jsonp

使用方法与axios相同

 

10.请求数据

原文:https://www.cnblogs.com/xuepangzi/p/11621141.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!