vue2.0-第三方插件axios请求数据方式

vue2.0-第三方插件axios请求数据方式

参考:https://github.com/axios/axios

 

1、安装axios

c:\Users\Administrator\Desktop\vuejs\vuejs\vuedemo>npm install axios --save

查看packages.json文件,查看安装记录。

  "dependencies": {

    "axios": "^0.18.0",

    "element-ui": "^2.4.11",

    "vue": "^2.5.2",

    "vue-resource": "^1.5.1",

    "vue-router": "^3.0.1"

  },

 

2、引用

在组件里面直接引用

import Axios from 'axios';

 

3、组件配置,

 

 

4、源代码

<template>

  <div class="hello">

    <button @click="getData()">请求数据</button>

            <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-component',

  data () {

    return {

      aaa: '我是一个首页组件',

      flag:true,

      list:[]

    }

  },

  methods:{

      getData(){

          var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=12&page=1';

          Axios.get(api).then((response)=>{

              this.list=response.data.result;

          }).catch((error)=>{

              console.log(error);

          })

        }

      },

      mounted(){  /*生命周期函数,mouted-页面加载即可刷新界面*/

          this.getData();

        }

      }

</script>

 

<style scoped>

  h2{

      color: red;

    }

</style>

=================================

第二个demo

$ cnpm install axios --save

组件内导入和执行。

import axios from 'axios';

<script>

import TodoItem from './components/TodoItem'

import axios from 'axios';

export default {

  data () {

    return {

      repoUrl: '',

      repoName: ''

    }

  },

  mounted () {

    // axios请求获取数据

    const url = `https://api.github.com/search/repositories?q=vue&sort=stars`

    axios.get(url).then(response => {

        //成功了

        const result = response.data

        //得到最受欢迎的repo地址

        const repoRepo = result.items[0]

        this.repoUrl = repoRepo.html_url

        this.repoName = repoRepo.name

      }).catch(error => {

        alert('请求失败了')

      })

  }

}

</script>

 

posted @ 2019-01-21 21:17  wang_wei123  阅读(224)  评论(0编辑  收藏  举报