Vue.js组件数据变量在方法中未定义

时间:2020-03-20 20:53:38

标签: javascript vue.js vue-component

我有这样的组件:

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。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您的this指的是replace函数上下文,而不是vues方法上下文

这样更改

return id.replace(someRegExp, (capture) => {
    //...
    if(cond) this.var2.push(id);
    return `<a href='/post/${id}'></a>`
});

以便上下文被正确绑定。或者,可以这样做

const self=this;
return id.replace(someRegExp, function (capture) {
    //...
    if(cond) self.var2.push(id);
    return `<a href='/post/${id}'></a>`
});

答案 1 :(得分:1)

您可以使用ES6的箭头功能,其中this指针将保留父级上下文。

return id.replace(someRegExp, (capture) => {
    //...
    if(cond) this.var2.push(id);
    return `<a href='/post/${id}'></a>`
});