vue-resource 与 axios 在架手架Vue-cli下使用

vue-resource (官方)使用<推荐使用>

步骤如下:

1、安装cnpm install vue-resource --save 或者npm install vue-resource --save

2、引入,在main.js引入,代码如下:

import VueResource from 'vue-resource'
Vue.use(VueResource);
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)
})

3、使用,使用的话可以在框架任何地方使用,如下:

getData2(){
        var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
           this.$http.get(api).then(response => {
           console.log(response);
            this.list2=response.data.result;
         }, response => {

            });
        }

参考地址:https://github.com/pagekit/vue-resource/

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

axios的使用:https://github.com/axios/axios(第三方)
1、安装 
npm install axios 或者 cnpm install axios
2、引入;在什么地方使用就必须在什么地方引用
import Axios from 'axios';
3、使用代码如下:
getData(){
        var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
            Axios.get(api).then((res)=>{
                console.log(res);
                this.list=res.data.result;

            }).catch((error)=>{
               console.log(error);
            })
        }

个人建议使用vue-resource 毕竟官方,以前看帖说不更新了,但是发现最近还在更新。

最终整体使用代码如下:

<template>
<div>
 <h1>这是一个组件</h1>
<button @click="getData()">获取数据</button>
<ul v-for="(item,key) in list">
    <li>
   {{item.title}}
    </li>
</ul>
<button @click="getData2()">获取数据2</button>
<ul v-for="(item,key) in list2">
    <li>{{item.title}}</li>
</ul>
</div>
    
</template>
<script>
import Axios from 'axios';
export  default {
    name:'home',
    data(){
        return {
            list:[]
            ,list2:[]

        }
    },methods:{
        getData(){
        var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
            Axios.get(api).then((res)=>{
                console.log(res);
                this.list=res.data.result;

            }).catch((error)=>{
               console.log(error);
            })
        }
        ,mounted(){
           
        },
    getData2(){
        var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
           this.$http.get(api).then(response => {
           console.log(response);
            this.list2=response.data.result;
         }, response => {

            });
        }

    }


 }
</script>

 

 
 

 

 

 

 

posted @ 2018-12-17 22:00  技术小代  阅读(258)  评论(0编辑  收藏  举报