axios在vue.cli3应用

axios

Posted by czkuo on April 11, 2019

axios在vue.cli3应用

axios特性(网上全是)

从浏览器中创建 XMLHttpRequests 从 node.js 创建 http 请求 支持 Promise API 拦截请求和响应 转换请求数据和响应数据 取消请求 自动转换 JSON 数据 客户端支持防御 XSRF

安装

npm (个人习惯npm)
$ npm install axios
bower
$ bower install axios
cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

例子

<template xmlns:v-on="http://www.w3.org/1999/xhtml">

  <div id="app">
    <!--<img alt="Vue logo" src="./assets/logo.png">-->
    <!--<HelloWorld msg="Welcome to Your Vue.js App"/>-->
    <div v-for="data in datas">
      <span>名字</span><input v-model="data.name" />
    </div>
    <button v-on:click="add">增加</button>
    <button v-on:click="sendget">发送get请求</button>
    <button v-on:click="sendpost">发送post请求</button>
    <ul class="demo">
      <li v-for="value in retdata">
        
      </li>
    </ul>
  </div>

</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import axios from 'axios';
export default {
  name: 'app',
    data(){
      return{
          retdata:{},
          datas:[{
              name:"czk"
          }]
      }
    },
    methods:{
        add:function(){
            let cope = {
                name:"",
            }
            this.datas.push(cope);
            console.log(this.datas)
        },
        sendget(){
            // var _this=this;
            console.log('进入axios');
            axios.get('czk/api/msdict/selectAll')
                .then(response=> {
                    console.log(response.data.data);
                    this.retdata=response.data.data;
                    console.log(this.retdata);
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        sendpost(){
            // var _this=this;
            console.log('进入axios');
            axios.post('czk/api/mscarbrand/insertCarBrand',
                {
                    carbrandCode:123
            })
                .then(response=> {
                    console.log(response.data.data);
                    this.retdata=response.data.data;
                    console.log(this.retdata);
                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    },
  components: {
      HelloWorld
  }
}
</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;
}
</style>

注意

返回值接收时 钥匙=>函数 或者 var _this=this 重新定义this指向

get请求例子
sendget(){
            var _this=this;
            console.log('进入axios');
            axios.get('czk/api/msdict/selectAll')
                .then(response=> {
                    console.log(response.data.data);
                    _this.retdata=response.data.data;
                    console.log(_this.retdata);
                })
                .catch(function (error) {
                    console.log(error);
                });
        }
发送端口以及跨域问题

在根目录(和package.json同级)创建vue.config.js文件,当vue.config.js不存在时vue.cli3试别node_modules中 @vue->cli-service

// vue.config.js 配置说明
// 这里只列一部分,具体配置惨考文档啊
module.exports = {
    // publicPath  type:{string} default:'/'
    // 将部署应用程序的基本URL
    // 将部署应用程序的基本URL。
    // 默认情况下,Vue CLI假设您的应用程序将部署在域的根目录下。
    // https://www.my-app.com/。如果应用程序部署在子路径上,则需要使用此选项指定子路径。例如,如果您的应用程序部署在https://www.foobar.com/my-app/,集baseUrl到'/my-app/'.

    publicPath: process.env.NODE_ENV === 'production' ? '/online/' : '/',

    // outputDir: 在npm run build时 生成文件的目录 type:string, default:'dist'

    // outputDir: 'dist',

    // pages:{ type:Object,Default:undfind }
    /*
      构建多页面模式的应用程序.每个“页面”都应该有一个相应的JavaScript条目文件。该值应该是一
      个对象,其中键是条目的名称,而该值要么是指定其条目、模板和文件名的对象,要么是指定其条目
      的字符串,
      注意:请保证pages里配置的路径和文件名 在你的文档目录都存在 否则启动服务会报错的
    */
    // pages: {
    // index: {
    // entry for the page
    // entry: 'src/index/main.js',
    // the source template
    // template: 'public/index.html',
    // output as dist/index.html
    // filename: 'index.html'
    // },
    // when using the entry-only string format,
    // template is inferred to be `public/subpage.html`
    // and falls back to `public/index.html` if not found.
    // Output filename is inferred to be `subpage.html`.
    // subpage: 'src/subpage/main.js'
    // },

    //   lintOnSave:{ type:Boolean default:true } 问你是否使用eslint
    lintOnSave: true,
    // productionSourceMap:{ type:Bollean,default:true } 生产源映射
    // 如果您不需要生产时的源映射,那么将此设置为false可以加速生产构建
    productionSourceMap: false,
    // devServer:{type:Object} 3个属性host,port,https
    // 它支持webPack-dev-server的所有选项

    devServer: {
        port: 8888, // 端口号
        host: 'localhost',
        https: false, // https:{type:Boolean}
        open: true, //配置自动启动浏览器
        // proxy: 'http://localhost:4000' // 配置跨域处理,只有一个代理
        proxy: {
            '/czk': {
                target: 'http://localhost:50020',   // 需要请求的地址
                changeOrigin: true,  // 是否跨域
                pathRewrite: {
                    '^/czk': '/'  // 替换target中的请求地址,也就是说,在请求的时候,url用'/proxy'代替'http://ip.taobao.com'
                }
            }

        },  // 配置多个代理
    }
}