admin管理员组文章数量:1429645
I have something like this as a ponent:
Vueponent
(
'myp',
{
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>`
});
}
}
}
);
The error I get here would be:
TypeError: "this.var2 is undefined"
and the source of the error points to func2
. What am I doing wrong ?
I have something like this as a ponent:
Vue.ponent
(
'myp',
{
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>`
});
}
}
}
);
The error I get here would be:
TypeError: "this.var2 is undefined"
and the source of the error points to func2
. What am I doing wrong ?
2 Answers
Reset to default 4Your this
refers to the replace
functions context, not vues method context
change it like this
return id.replace(someRegExp, (capture) => {
//...
if(cond) this.var2.push(id);
return `<a href='/post/${id}'></a>`
});
So that the context is bound properly. Or alternatively, do this
const self=this;
return id.replace(someRegExp, function (capture) {
//...
if(cond) self.var2.push(id);
return `<a href='/post/${id}'></a>`
});
You can use ES6's arrow functions, where the this
pointer will retain the context of the parent.
return id.replace(someRegExp, (capture) => {
//...
if(cond) this.var2.push(id);
return `<a href='/post/${id}'></a>`
});
本文标签: javascriptVuejs component data variable undefined in methodStack Overflow
版权声明:本文标题:javascript - Vue.js component data variable undefined in method - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745549436a2662864.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论