...

Vue学习笔记03-Axios

目录

Axios

13. Vue-axios基础Get请求

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

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

中文: https://www.kancloud.cn/yunye/axios/234845
github: https/github.com/axios/axios

(1)安装 npm install axios --save
(2)main.js中引入加载

import Axios form "axios"
Vue.prototype.$axios = Axios

(3)请求

this.$axios.get("http://127.0.0.1/add/",{params: {a: "1",b: "2"}})
    .then(res=> {this.result = res.data;})
    .catch(error=> {console.log(error); })

也可使用通用的this.$axios({method:"get", url: '', params: {}, data: {}})

this.$axios({
      method: 'get',
      url: 'https://httpbin.org/get',
      params: {name: '临渊', age: 18, sex: '男'}
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

示例:
src/main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Axios from 'axios'  // 导入

import App from './App'

Vue.config.productionTip = false  // 生产环境配置提示

Vue.prototype.$axios = Axios  // 挂载到原型的$axios上

/* eslint-disable no-new */
new Vue({
  el: '#app',  // 绑定根视图
  components: { App },  // 加载组件
  template: '<App/>'  // 使用组件
})

src/App.vue

<template>
  <div id="app">
    {{ data }}
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return {
      data: {}
    }
  },
  created(){
    // this.$axios.get('https://httpbin.org/get?name=临渊&age=18', { params: {sex: '男'} })
    // .then(res=> { this.data=res.data })
    // .catch(error=> { console.log(error) })
    this.$axios({
      method: 'get',
      url: 'https://httpbin.org/get',
      params: {name: '临渊', age: 18, sex: '男'}
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

  }
}
</script>
<style lang="css">
</style>

14. Vue-axios基础Post请求

发送表单格式数据

  • this.$axios.post('https://httpbin.org/post', "name=临渊&age=18&sex=男")

或使用qs将对象转为urlencoded字符串 (需要导入qs)

this.$axios.post('https://httpbin.org/post', qs.stringify({name: '临渊', age: '18', sex: '男'}))

通用请求方式

this.$axios({
      method: 'post',
      url: 'https://httpbin.org/post',
      data: "name=临渊&age=18&sex=男"  // 或 qs.stringify({name: '临渊', age: '18', sex: '男'})
    })

示例:
src/main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Axios from 'axios'  // 导入

import App from './App'

Vue.config.productionTip = false  // 生产环境配置提示

Vue.prototype.$axios = Axios  // 挂载到原型的$axios上

/* eslint-disable no-new */
new Vue({
  el: '#app',  // 绑定根视图
  components: { App },  // 加载组件
  template: '<App/>'  // 使用组件
})

src/App.vue

<template>
  <div id="app">
    {{ data }}
  </div>
</template>

<script>
import qs from "qs"
export default {
  name: 'App',
  data(){
    return {
      data: {}
    }
  },
  created(){
    // this.$axios.post('https://httpbin.org/post', "name=临渊&age=18&sex=男")
    // this.$axios.post('https://httpbin.org/post', qs.stringify({name: '临渊', age: '18', sex: '男'}))
    // .then(res=> { this.data=res.data })
    // .catch(error=> { console.log(error) })
    this.$axios({
      method: 'post',
      url: 'https://httpbin.org/post',
      data: "name=临渊&age=18&sex=男"  // 或 qs.stringify({name: '临渊', age: '18', sex: '男'})
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

  }
}
</script>

<style lang="css">

</style>

发送JSON请求

this.$axios.post('https://httpbin.org/post', {name: '临渊', age: '18', sex: '男'})

this.$axios({
      method: 'post',
      url: 'https://httpbin.org/post',
      data: {name: '临渊', age: '18', sex: '男'} 
    })

全局的axios默认值

main.js中, Vue.prototype.$axios = Axios;

Axios.defaults.baseURL = 'http://127.0.0.1:5000';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Axios.defaults.headers.comont['Authorization'] = AUTH_TOKEN;

15. Vue-axios全局配置与拦截器

全局默认配置

在src/main.js可以添加Axios的全局配置,如

Axios.defaults.baseURL = 'https://httpbin.org';
axios.defaults.headers.common['Authorization'] = '123';
Axios.defaults.headers.post['x-test'] = 'abc';

拦截器

在发送发送请求前或接收响应后执行指定函数。
在src/main.js中添加

  • 拦截请求:Axios.interceptors.request.use(function(config){})
  • 拦截响应:Axios.interceptors.response.use(function(response){})

例如:

// 添加请求拦截器
Axios.interceptors.request.use(function(config) {
    if (config.method == "post") {
        config.data = qs.stringify(config.data);  //将所有post对象转为表单格式
    }
    return config;

}, function(error) {
    //对请求错误做些什么
    return Promise.reject(error);

});

// 添加响应拦截器
Axios.interceptors.response.use(function(response) {
    return response;

}, function(error){
    //对响应错误做点什么
    return Promist.reject(error);
}
)

示例:
src/main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Axios from 'axios'  // 导入

import App from './App'

Vue.config.productionTip = false  // 生产环境配置提示

Vue.prototype.$axios = Axios  // 挂载到原型的$axios上

Axios.defaults.baseURL = 'https://httpbin.org';
Axios.defaults.headers.post['x-test'] = 'abc'


Axios.interceptors.request.use(function(config){
    console.log(config);
    return config
})

Axios.interceptors.response.use(function(response){
    console.log(response);
    return response
})

/* eslint-disable no-new */
new Vue({
  el: '#app',  // 绑定根视图
  components: { App },  // 加载组件
  template: '<App/>'  // 使用组件
})

src/App.vue

<template>
  <div id="app">
    {{ data }}
  </div>
</template>

<script>
import qs from "qs"
export default {
  name: 'App',
  data(){
    return {
      data: {}
    }
  },
  created(){
    this.$axios({
      method: 'post',
      url: '/post',
      data: 'name=临渊&age=18' 
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

  }
}
</script>

<style lang="css">
</style>

16. Vue-axios跨域处理

调试时如何使用数据

使用mock模拟数据

  1. 自己创建JSON文件, 使用get请求形式访问数据
    1. 优点: 方便,快捷
    2. 缺点: 只能存在get请求
  2. 项目中集成服务器, 模拟各种接口
    1. 优点: 模拟真实线上环境
    2. 缺点: 增加开发成本
  3. 直接使用线上数据
    1. 优点: 使用
    2. 不一定每个项目都存在

使用后端接口

如使用Axios直接请求

created(){
    this.$axios.get('http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0')
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })
  }

Chrome Console面板会报跨域错误,如下:

Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

需要解决跨域问题,解决方式,使用Nodejs后端服务作为请求中转来解决跨域问题,方式如下:

  1. 修改config/index.js文件dev端的proxyTable(只对开发环境生效),添加api配置,并重启(修改配置后需要重启才能生效)
    // 解决跨域问题
    proxyTable:{
        "/api": {
            target: "http://tingapi.ting.baidu.com",
            changeOrigin: true,
            pathRewrite: {
                "^/api": ""
            }
        }
    },
  1. src/main.js中读取配置并绑定到原型的HOST属性上
    Vue.prototype.HOST = '/api';
  2. 组件中重新组装url
    var url = this.HOST + "v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0";

示例:
config/index.js

...
module.exports = {
  dev: {
    ...
    proxyTable: {
        '/api': {
            target: "http://tingapi.ting.baidu.com",
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
    ...

src/main.js

import Vue from 'vue'
import Axios from 'axios'  // 导入Axios
import App from './App'

Vue.config.productionTip = false  // 生产环境配置提示
Vue.prototype.$axios = Axios  // 挂载到原型的$axios上
Vue.prototype.HOST = {baiduting: '/api'}  // 支持绑定多个
new Vue({
  el: '#app',  // 绑定根视图
  components: { App },  // 加载组件
  template: '<App/>'  // 使用组件
})

src/App.vue

<template>
  <div id="app">
    <h2>最火歌曲</h2>
    <ul>
      <li v-for="(item,index) in songList">{{ index + 1 }}. {{ item.author }} - {{ item.title }}</li>
    </ul>
  </div>
</template>
<script>
import qs from "qs"
export default {
  name: 'App',
  data(){
    return {
      songList: []
    }
  },
  created(){
    var url = this.HOST.baiduting + '/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0'
    this.$axios.get(url)
    .then(res=> { this.songList=res.data.song_list })
    .catch(error=> { console.log(error) })
  }
}
</script>
<style lang="css">
</style>

17. Vue操作原始DOM

Vue直接操作原始DOM(不推荐)

  • template中节点使用ref="名称"绑定
  • scripts中使用this.$refs.名称来引用节点

示例:
src/App.vue

<template>
  <div id="app">
    <p ref="myp">哈哈</p>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return {
    }
  },
  mounted(){
    console.log(this.$refs.myp.innerHTML='嘿嘿');
    console.log(this.$refs.myp.style.color='red');
    this.$refs.myp.addEventListener("click", function(){console.log('clicked');})  // 添加时间
  }
}
</script>
<style lang="css">
</style>

使用jQuery操作DOM

(1)安装jQuery cnpm install --save jquery,重启项目
(2)组件中引入jQuery import $ from "jquery"
(3)组件中使用 $('#myp').css("color", "red")

示例:
src/App.vue

<template>
  <div id="app">
    <p id="myp">哈哈</p>
  </div>
</template>
<script>
import $ from "jquery"
export default {
  name: 'App',
  data(){
    return {
    }
  },
  mounted(){
    $('#myp').css("color", "red");
  }
}
</script>
<style lang="css">
</style>
posted @ 2020-04-29 17:51  韩志超  阅读(321)  评论(0编辑  收藏  举报