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 ?

Share Improve this question asked Mar 20, 2020 at 20:53 Robert C. HollandRobert C. Holland 1,8135 gold badges33 silver badges61 bronze badges
Add a ment  | 

2 Answers 2

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

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