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

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

最佳答案

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

这样改

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

以便正确绑定(bind)上下文。或者,执行此操作

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

关于javascript - Vue.js 组件数据变量在方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60781490/

相关文章:

javascript - 过滤JS问题

vue.js - vue : add custom property to "this" inside component, 并防止被添加 "__ob__"和 getter/setter

javascript - 关于 Vue 模板中的更改未被解雇

php - 如何在不使用 FormData 的情况下在 Web Workers 中上传文件

javascript - Vuejs:将代码分布在多个组件或所有组件中吗?

javascript - AJAX 响应应更新 while 循环结果中的所有记录

vue.js - 如何使用 Nuxt.js 仅在一个组件中使用插件?

vue.js - VueJS 2 : Watch method trigger in a component

java - 如何从 JavaScript 调用带有 JSP Servlet 参数的操作?

javascript - .getElementById IE