Vue学习11----数据请求模块vue-resource(推荐)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaihaohao1/article/details/88993331

vue-resource 是Vue官方自带的数据请求模块
参考文档:
https://www.npmjs.com/package/vue-resource
https://github.com/pagekit/vue-resource/blob/HEAD/docs/http.md

下面我写了一个例子
效果图:
在这里插入图片描述

项目结构:
在这里插入图片描述

使用vue-resource请求数据的步骤
1、需要安装vue-resource模块, 注意加上 --save
npm install vue-resource --save / cnpm install vue-resource --save
2、main.js引入 vue-resource
import VueResource from ‘vue-resource’;
3、main.js Vue.use(VueResource);
4、在组件里面直接使用
this.$http.get(地址).then(function(){
})
main.js中

import Vue from 'vue'
import App from './App.vue'
import vueresource from 'vue-resource'
Vue.use(vueresource);

new Vue({
  el: '#app',
  render: h => h(App)
})

App.vue 中

<!--参考文档:vue官方提供-->
<!--https://www.npmjs.com/package/vue-resource-->
<!--https://github.com/pagekit/vue-resource/blob/HEAD/docs/http.md-->

<template>

  <div>
    <button @click="httpData()">get请求数据</button>
    <br/>
    <!--渲染请求到的数据-->
    <ul>
      <li v-for="item in list">
        {{item.title}}
      </li>
    </ul>
  </div>
</template>

<script>
  /*
使用vue-resource请求数据的步骤
1、需要安装vue-resource模块,  注意加上  --save
npm install vue-resource --save /  cnpm install vue-resource --save
2、main.js引入 vue-resource
import VueResource from 'vue-resource';
3、main.js  Vue.use(VueResource);
4、在组件里面直接使用
this.$http.get(地址).then(function(){
})
*/
  export default {
    name: 'app',
    data() {
      return {
        msg: 'Welcome to Your Vue.js App',
        list: [],
      }
    },
    methods: {
      httpData() {
        //请求数据
        var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
        this.$http
          .get(api)
          .then((response) => {
            console.log(response);
            //注意this指向(箭头函数中this,才能指向data中的数据)
            this.list = response.body.result;
            console.log(this.list);
          }, err => {
            console.log(err);

          })


      }
    }
  }
</script>

<style lang="scss">
  button{
    width: 100%;
    height: 100px;
    font-size: 30px;

  }

</style>

源码下载:

猜你喜欢

转载自blog.csdn.net/zhaihaohao1/article/details/88993331