【发布时间】: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