時間: 2019-8-8
ok,我們今天講解一下,如何在aixos的攔截器裏拿到 當前調用它的 this(vue實例)的一些屬性和方法!
axios.js文件
import axios from 'axios'
import Vue from 'vue'
let myAxios = axios.create({
baseURL: 'xxx/api/',
timeout: 5000
})
Vue.prototype.$axios = myAxios
myAxios.interceptors.request.use(function (config) {
switch (config.method) {
case 'get':
// ---------------------------
// config.params.that.x (這裏的.that就是當前vue實例)
config.that = config.params.that
config.that.data.x = 456
config.that.getX()
// ---------------------------
delete config.params.that
break
case 'post':
// ---------------------------
// config.data.that.x (這裏的.that就是當前vue實例)
config.that = config.data.that
config.that.data.x = 456
config.that.getX()
// ---------------------------
delete config.data.that
break
}
return config;
}, function (error) {
return Promise.reject(error);
})
myAxios.interceptors.response.use(function (response) {
return response;
}, function (error) {
// error.config.that.data
// error.config.that.data.x = 1
return Promise.reject(error);
})
main.js
import Vue from 'vue'
import App from './App.vue'
import './axios'
new Vue({
el: '#app',
render: h => h(App)
})
App.vue
<template>
<div></div>
</template>
<script>
export default {
data () {
return {
x: 123
}
},
watch: {
x () {
console.log('watch')
}
},
created () {
this.$axios.get('getList', {
params: {
that: {
data: this.$data,
getX: this.getX
}
}
}).then(res => {})
},
methods: {
getX () {
console.log(this)
console.log(this.x)
this.x = 789
}
}
}
</script>
1. get 請求外層必須加 params,post 請求外層必須加 data.
因爲 axios 對傳入的 key 進行了對比,把自己不需要的值直接忽略了,所以我們只能通過它自帶的參數傳進去。(雖然 get 請求也會拿到 data 但是它不會傳給後臺。本着少穿一個參數的意思,所以我們 get 就params, post 就 data)
2. 這裏避免把 this 直接傳入到 that.
因爲 vnode 這個對象是非常大的,傳過來傳過去不好。而且這裏不能直接把 this.x 傳過去,因爲這樣會不響應!我們這樣寫正是利用了 js 的淺拷貝。
3. 用完之後需要刪除。
不刪除的話,會把參數帶入給後臺。
4. 我們可以直接 getX 傳入 this.getX.
利用 js 的閉包。
5. 之後我們把傳件來的 this 實例屬性給 config.that.
這樣我們可以在其他地方,比如 response 這裏的 error 通過 error.config.that 來讀取
如果大家有更好的方法,歡迎指正。