programing

Vue 리소스 - http 메서드를 동적으로 결정합니다.

randomtip 2022. 8. 30. 21:53
반응형

Vue 리소스 - http 메서드를 동적으로 결정합니다.

적절한 http 메서드를 동적으로 결정하고 단일 api 콜을 발신하고 싶습니다.그러나 메서드를 호출하면 예외가 발생합니다.

저는 제가 이 일을 하는 것보다 뭔가 잘못된 일을 하고 있다고 생각합니다.vue-resource벌레요. 조언해 주실 분 있나요?고마워요.

예를 들어 다음과 같습니다.

let method = this.$http.post

if (this.model.id) {
    method = this.$http.put
}

method(
    this.url,
    this.model,
    options
).then(response => {
    this.$router.push(this.redirect_to)
}).catch(response => {
    console.log(`Error: ${response.statusText}`)
})

자바스크립트TypeError"이것은 함수가 아닙니다"라는 메시지와 함께 느려집니다.


아래 코드는 동작하고 있습니다만, 조금 길게 설정되어 있습니다.

if (this.model.id) {
    this.$http.put(
        this.url,
        this.model,
        options
    ).then(response => {
        this.$router.push(this.redirect_to)
    }).catch(response => {
        console.log(`Error: ${response.statusText}`)
    })

} else {
    this.$http.post(
        this.url,
        this.model,
        options
    ).then(response => {
        this.$router.push(this.redirect_to)
    }).catch(response => {
        console.log(`Error: ${response.statusText}`)
    })
}

함수를 현재 컨텍스트에 바인딩해야 합니다.

let method = this.model.id ? this.$http.put.bind(this) : this.$http.post.bind(this)

또는 인덱서 접근 방식을 사용할 수도 있습니다.

let method = this.model.id ? 'put' : 'post'
this.$http[method](...).then(...)

언급URL : https://stackoverflow.com/questions/45804437/vue-resource-dynamically-determine-http-method

반응형