2

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 ?

2 Answers 2

4

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>`
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'll accept it as answer after the minimum time limit. My application hangs after fixing this line, clearly for some other problem, is there anything obvious that you notice from what I posted that might be causing the problem ?
@RobertC.Holland I don't see anything obvious in it. Can you post a fiddle or something of the problem? I would probably have used a computed, not a function for this. Even a custom filter that applies the regex would work
It was related to using method instead of computed, it has been resolved, thank you.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.