代码之家  ›  专栏  ›  技术社区  ›  pymarco

Vue资源-动态确定http方法

  •  3
  • pymarco  · 技术社区  · 7 年前

    我希望我做错了什么,而不是这是一个错误 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}`)
    })
    

    javascript 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}`)
        })
    }
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Bert Jeffrey Shen    7 年前

    您需要将函数绑定到当前上下文。

    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(...)