Robert C. Holland
Robert C. Holland

Reputation: 1813

Vue.js component data variable undefined in method

I have something like this as a 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>`
                });
            }
        }
     }
  );

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 ?

Upvotes: 2

Views: 4924

Answers (2)

Trevor
Trevor

Reputation: 2922

Your 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>`
});

Upvotes: 4

Daniel F
Daniel F

Reputation: 14239

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>`
});

Upvotes: 1

Related Questions