vue+axios安裝


Axios是一個基於promise的HTTP庫,可以用在瀏覽器和node.js中。

安裝方式:

1.使用cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2.使用npm安裝

npm/cnpm install axios

在main.js中import axios並將其掛載到Vue實例上

import Axios from 'axios'
Vue.prototype.$axios = Axios //調用時使用this. $axios()

3.點擊隨機切換笑話的小例子

<template>
  <div id="app">
    <input type="button" name id value="獲取笑話" @click="getJoke" />
    <p>{{joke}}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => {
    return {
      joke: "很好笑的笑話"
    };
  },
  methods: {
    getJoke: function() {
      // axios回調函數中的this已經改變,無法訪問到data中數據
      // 可以var that = this; 回調函數中用that訪問data中數據
      var that=this;
      this.$axios({
        url: "https://autumnfish.cn/api/joke",
        methods: "get"
      }).then(
        function(response) {
          console.log(response.data);
          that.joke=response.data
        },
        function(err) {}
      );
    }
  },
  created: function() {}
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

ul,
li {
  list-style: none;
}
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM