Vue 之 axios 使用

40 阅读1分钟

1.0 推荐使用 vue-resource 库。

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

首先安装

npm install axios

这里我定一个 组件

AjaxTest.vue


<template>

  <div class="hello">
<!--    没有值显示-->
    <div v-if="!url1">loding</div>
    <div v-else>most stat repo is <a :href="url1"> {{url1Name}}</a></div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AjaxTest',
  data () {
    return {
      url1:'',
      url1Name:''
    }
  },
  //页面加载时请求
  mounted(){
    const url = 'https://api.asilu.com/weather/weather/?callback=jQuery19106109457892611343_1570371308404&id=101010100&_=1570371308408'
    axios
      .get(url)
      .then(response => (
        this.url1Name = response.data
          ,
        this.url1 = url
      ))
      .catch(function (error) {// 请求失败处理
        alert("错误")
      })
  }

}
</script>

<style>
h1 {
  font-weight: normal;
}
hello a {
  font-size: 30px;
  color: #42b983;
}
</style>