在做vue项目时用到了axios,但是发现axios请求之后的回调函数里this并不指向当前vue实例,从而导致浏览器报错。
出错代码及结果:
created : function(){
axios.get('static/data.json').then(function(res){
console.log(this) //undefined
this.user = res.data.user
})
}
(报错截图)
普通函数代码改版(正确):
created : function(){
var _this = this
axios.get('static/data.json').then(function(res){
console.log(this) //undefined
console.log(_this) //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
_this.user = res.data.user
})
}
从以上结果来看,在created下的函数this指向的是当前创建的vue实例,而在这些函数内部使用例如axios与后台交互后回调函数的内部的this并非指向当前的vue实例;
若想拿到后台回传的数据更新data里的数据,不能在回调函数中直接使用this,而要用在外部函数定义的变量存储的this,也就是当前vue的实例。
箭头函数代码改版(正确):
created : function(){
axios.get('static/data.json').then((res) => {
console.log(this) //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
this.user = res.data.user
})
}
箭头函数相当于匿名函数,并且简化了函数定义。看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。此时this在箭头函数中已经按照词法作用域绑定了。很明显,使用箭头函数之后,箭头函数指向的函数内部的this已经绑定了外部的vue实例了.
<template>
<div id="example">
<button @click="decrement">-</button>
{{count}}
{{dataCount}}
<button @click="increment">+</button>
<div>{{sex}}</div>
<div>{{from}}</div>
<div>{{myCmpted}}</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data () {
return {
str: '国籍',
dataCount: this.$store.state.count
}
},
computed: mapState({
count: 'count', // 第一种写法
sex: (state) => state.sex, // 第二种写法
from: function (state) { // 用普通函数this指向vue实例,要注意
return this.str + ':' + state.from
},
// 注意下面的写法看起来和上面相同,事实上箭头函数的this指针并没有指向vue实例,因此不要滥用箭头函数
// from: (state) => this.str + ':' + state.from
myCmpted: function () {
// 这里不需要state,测试一下computed的原有用法
return '测试' + this.str
}
}),
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
},
created () {
// 写个定时器,发现computed依旧保持了只要内部有相关属性发生改变不管是当前实例data中的改变,还是vuex中的值改变都会触发dom和值更新
setTimeout(() => {
this.str = '国家'
}, 1000)
}
}
</script>