【问题标题】:Vue resource - dynamically determine http methodVue资源-动态确定http方法
【发布时间】:2018-01-29 23:03:57
【问题描述】:

我想动态确定适当的 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}`)
})

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

【问题讨论】:

  • let method = this.$http.post 这段代码在哪里?在方法中?
  • 也许可以试试let method = (this.model.id) ? 'put' : 'post'; this.$http[method](this.url, this.model, options) ...
  • 是的,代码示例来自“方法”方法。

标签: javascript vue.js vuejs2 vue-resource


【解决方案1】:

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

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

【讨论】:

  • 我喜欢索引器方法,效果很好!再次感谢!!
猜你喜欢
  • 2016-07-19
  • 2017-05-19
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 2016-11-04
  • 1970-01-01
  • 2016-03-23
相关资源
最近更新 更多