programing

Vuex에서 이를 바인드한 후 콜백하는 방법

itsource 2022. 7. 29. 23:36
반응형

Vuex에서 이를 바인드한 후 콜백하는 방법

앱에서 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>

여기서 화살표 함수에 대한 설명서를 읽었는데 화살표 함수는 자체 생성되지 않는다고 합니다.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>

언급URL : https://stackoverflow.com/questions/46705053/how-to-bind-this-in-then-callback-in-vuex

반응형