我在我的应用中使用Vuex。我在组件内部调度一个动作。我在then()
收到了结果。我需要将部分结果分配给Vue组件中定义的一些局部变量。如果我将then()
与this
绑定,我只能这样做。有没有办法在不使用bind
的情况下实现相同目的。
这是我的原始代码,我在讨论第this.$store.dispatch
行:
<script>
/* eslint-disable */
import * as d3 from 'd3'
import FlightCard from './FlightCard'
export default {
name: 'AirportLayout',
components: {FlightCard},
props: ['id'],
data () {
return {
cardActivator: null
}
},
methods: {
// show flight card menu
showFlightCard: function (e) {
// debugger
let flight = this.$store.state.demo.find(a => {
return a.flightNr === e.target.id
})
this.$store.dispatch('getFlightCard', {flightNr: flight.flightNr, scheduledDate: flight.scheduledDate}).then(function (){
debugger
// here I want to do something with the response
this.cardActivator = document.getElementById(e.target.id)
console.log('Showing flight card for: ', this.cardActivator)
}.bind(this)) // Using bind, this gets the value of Vue component
}
}
}
</script>
我在这里阅读了箭头函数的文档Arrow functions,它说箭头函数没有创建自己的this
,而是使用了封闭执行上下文的this
值。我假设这将是Vue组件,我尝试了,但后来this
值为undefined
。所以我总结出执行上下文必须是指then()
,我是对的吗?如果是,我如何在this
内then()
引用Vue组件?
这是我使用箭头功能的代码
<script>
/* eslint-disable */
import * as d3 from 'd3'
import FlightCard from './FlightCard'
export default {
name: 'AirportLayout',
components: {FlightCard},
props: ['id'],
data () {
return {
cardActivator: null
}
},
methods: {
// show flight card menu
showFlightCard: function (e) {
// debugger
let flight = this.$store.state.demo.find(a => {
return a.flightNr === e.target.id
})
this.$store.dispatch('getFlightCard', {flightNr: flight.flightNr, scheduledDate: flight.scheduledDate}).then(r => {
debugger
// here I want to do something with the response
this.cardActivator = document.getElementById(e.target.id)
console.log('Showing flight card for: ', this.cardActivator)
}) // here the value for this is undefined
}
}
}
</script>