1. 程式人生 > >Vue-cli簡單的使用axios和開發環境下跨域

Vue-cli簡單的使用axios和開發環境下跨域

官方說法:Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
這裡是英文文件和在kancloud上發現的中文文件

在vue專案下進行安裝(這裡用的是vue-cli建立的專案簡單的使用示例)

$ npm i axios

進入src/main.js引入axios

import axios from 'axios'
Vue.prototype.axios = axios//在Vue原型下面新增,axios不是外掛,無法使用vue.use()

開啟components/HelloWorld.vue 程式碼如下:

<template>
<div class="hello"> <h1>
{{ msg }}</h1> <button @click="seachbook">seach</button> <p>{{books}}</p> </div> </template> <script> export default { name: 'HelloWorld', data () { return { msg: 'Welcome', books: ''
} }, methods: { seachbook: function(){ this.axios.get('./static/test.json').then(function(response){ this.books = response.data.title }.bind(this)) //修改this指向,可以不寫bind(this),可改成ES6的寫法 response=>this.books = response.data.title } } }
</script>

然後在static資料夾新增一個test.json檔案,內容如下:

{
  "title": "javascript"
}

回到頁面點選按鈕,把javascript顯示出來表示請求成功(這裡並不是跨域)。
這裡寫圖片描述

接下來簡單的配置一下,用豆瓣的api試試跨域
開啟config/index.js,新增修改如下

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api':{ 
        target: 'https://api.douban.com/v2/', 
        changeOrigin: true, 
        pathRewrite: { 
        '^/api': ''
        } 
        } 
    },

開啟components/HelloWorld.vue 程式碼如下:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <input type="text" v-model="message" @keyup.enter="seach">
    <button @click="seach">seach</button>
    <p>{{message}}</p>
    <ul>
      <li v-for="item in booklist" v-text="item"></li>
    </ul>

  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      message: "",
      msg: "HelloWorld",
      booklist: []
    };
  },
  methods: {
    seach: function() {
      // var _this = this
      this.axios
        .get("/api/book/search?q=" + this.message)
        .then(
          function(response) {
            const bookdata = response.data.books;
            bookdata.forEach(function(val) {
              this.booklist.push(val.title)
            }.bind(this));
          }.bind(this)
        )
        .catch(function(response) {
          console.log(response);
        });
    }
  }
};
</script>

開啟頁面,我們試試搜尋一下javascript,可見如下,把書名列了出來(來自豆瓣讀書)
這裡寫圖片描述
就這麼多