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,可见如下,把书名列了出来(来自豆瓣读书)
这里写图片描述
就这么多

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值