我有这样的组件:
Vue.component
(
'mycomp',
{
props : ['c'],
data : function()
{
return { var1 : true, var2 : [] }
},
template : `<div v-html='func1(c.id)'></div>`,
methods :
{
func1(id)
{
// ...
return func2(id);
},
func2(id)
{
var someRegExp = /blah/ig;
return id.replace(someRegExp, function(capture)
{
//...
if(cond) this.var2.push(id);
return `<a href='/post/${id}'></a>`
});
}
}
}
);
我在这里得到的错误是:
TypeError: "this.var2 is undefined"
并且错误源指向 func2
。我做错了什么?
最佳答案
您的 this
指的是 replace
函数上下文,而不是 vues 方法上下文
这样改
return id.replace(someRegExp, (capture) => {
//...
if(cond) this.var2.push(id);
return `<a href='/post/${id}'></a>`
});
以便正确绑定(bind)上下文。或者,执行此操作
const self=this;
return id.replace(someRegExp, function (capture) {
//...
if(cond) self.var2.push(id);
return `<a href='/post/${id}'></a>`
});
关于javascript - Vue.js 组件数据变量在方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60781490/