pym*_*rco 3 javascript vue.js vue-resource vuejs2
我想动态确定适当的 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}`)
})
Run Code Online (Sandbox Code Playgroud)
一个 javascriptTypeError被抛出消息“这不是一个函数”
下面的代码有效,但有点啰嗦。
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}`)
})
}
Run Code Online (Sandbox Code Playgroud)
您需要将函数绑定到当前上下文。
let method = this.model.id ? this.$http.put.bind(this) : this.$http.post.bind(this)
Run Code Online (Sandbox Code Playgroud)
或者只是使用索引器方法。
let method = this.model.id ? 'put' : 'post'
this.$http[method](...).then(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |