Search code examples
javascriptvue.jsvuejs2vue-resource

Vue resource - dynamically determine http method


I would like to dynamically determine the appropriate http method and make a single api call. However an exception is thrown when I call the method.

I expect that I am doing something wrong rather than this being a vue-resource bug. Would anyone have any advice? Thanks

For example:

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}`)
})

A javascript TypeError is thrown with message "this is not a function"


The code below works, but a bit long winded.

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}`)
    })
}

Solution

  • You need to bind the function to the current context.

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

    Or just use the indexer approach.

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