如何从 Vue 中的回调访问本地组件变量?
2018-05-13
4286
我正在尝试使用 api rest 命令设置我的组件变量。我想通过其自己的文件中名为 handleResponse() 的函数来处理所有响应,如下所示。
// api/tools/index.js
function handleResponse (promise, cb, cbError) {
var cbErrorRun = (cbError && typeof cb === "function")
promise.then(function (response) {
if (!response.error) {
cb(response)
}
else if (cbErrorRun) {
cbError(response)
}
}).catch(function (error) {
console.log(error)
if (cbErrorRun) {
var responseError = {
"status": 404,
"error": true,
"message": error.toString()
}
cbError(responseError)
}
})
}
export {handleResponse}
在我的组件文件中,我有这个
.... More above....
<script>
import { fetchStock } from '@/api/stock'
export default {
data () {
return {
stock: {},
tabs: [
{
title: 'Info',
id: 'info'
},
{
title: 'Listings',
id: 'listings'
},
{
title: 'Company',
id: 'company'
}
],
}
},
validate ({params}) {
return /^\d+$/.test(params.id)
},
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
function(response) { //on successful data retrieval
this.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
}
</script>
当前代码给了我这个错误:“未捕获(在承诺中)TypeError:无法设置 undefinedAc 的属性‘stock’”。我认为发生这种情况是因为我无法再访问传入 fetchStock 函数的回调中的“this”。如何在不更改当前 handleResponse 布局的情况下修复此问题。
2个回答
你可以试试这个技巧
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
var self = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
ittus
2018-05-13
您可以使用箭头函数进行回调,因为箭头函数维护并使用其包含范围的
this
:
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
(response) => { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
(responseError) => { //on error
console.log(responseError)
}
)
}
或者您可以在回调之前在方法的开头分配
const vm = this
,就像这样。
vm stands for "View Model"
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
const vm = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
I advise using the
const
as opposed tovar
in thevm
declaration to make it obvious the value ofvm
is a constant.
Kelvin Omereshone
2020-08-27