3.vue请求数据

请求数据的方式:php

  • vue-resource 官方提供的 vue的一个插件
  • axios
  • fetch-jsonp

vue-resource的使用

使用步骤:
一、安装vue-resource模块vue

cnpm install vue-resource --save

二、在 main.js 引入 vue-resourceios

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

三、在组件里面直接使用npm

this.$http.get(地址).then(function(){

})

实例:
Info.vuejson

<template>
    <div id="info">
        <button @click="getData">获取数据</button>
        <ul>
            <li v-for="(item,index) in list" v-bind:key="index">
                {{item.title}}
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Info",
        data() {
            return {
                list: []
            }
        },
        methods: {
            getData: function () {
                let api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
                //此处推荐使用箭头函数。
                this.$http.get(api).then((res)=>{
                    this.list = res.body.result;
                }, (err)=>{
                    console.log(err);
                });
            }
        },
        mounted() {
            this.getData();
        }
    }
</script>

若是getData()中不适用箭头函数,就须要注意this问题。axios

getData: function () {
    let api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
    const _this = this;
    this.$http.get(api).then(function (res) {
        _this.list = res.body.result;
    }, function (err) {
        console.log(err);
    });
}

axios 的使用

axios 与 fetch-jsonp 同为第三方插件
一、安装api

cnpm  install  axios --save

二、哪里用哪里引入axiosapp

Axios.get(api).then((response)=>{
    this.list=response.data.result;
}).catch((error)=>{
    console.log(error);
})

fetch-jsonp 的使用

一、安装函数

cnpm  install  fetch-jsonp --save

二、哪里用哪里引入axiosvue-resource

fetchJsonp('/users.jsonp')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })
相关文章
相关标签/搜索