zoukankan      html  css  js  c++  java
  • 10.请求数据

    在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相同

  • 相关阅读:
    es5预览本地文件、es6练习代码演示案例
    Java实现 LeetCode 838 推多米诺(暴力模拟)
    Java实现 LeetCode 838 推多米诺(暴力模拟)
    Java实现 LeetCode 838 推多米诺(暴力模拟)
    Java实现 LeetCode 837 新21点(DP)
    Java实现 LeetCode 837 新21点(DP)
    Java实现 LeetCode 837 新21点(DP)
    Java实现 LeetCode 836 矩形重叠(暴力)
    Subversion under Linux [Reprint]
    Subversion how[Reprint]
  • 原文地址:https://www.cnblogs.com/xuepangzi/p/11621141.html
Copyright © 2011-2022 走看看