【问题标题】:How to use variables of data function on VueJS?如何在 VueJS 上使用数据函数的变量?
【发布时间】:2018-01-24 09:52:55
【问题描述】:

我对 VueJS 有一个愚蠢的问题。我是 VueJS 的新手。我想访问和更改数据函数的变量。但是我做不到。

出错的行:

console.log('item: ' + this.item);

错误在这里:

TypeError:无法读取未定义的属性“项目”

这是我的代码:

data: function(){
    return {
        item: 69,
        file: 0
    };
},

methods: {
    toggle: (elementId = 0, type = 'item') => {
        console.log('element ID: ' + elementId);
        console.log('type: ' + type);
        console.log('item: ' + this.item);

        switch (type) {
            case 'item':
                break;
            case 'file':
                break;
        }
    }
}

【问题讨论】:

  • console.log('item: ' + this.item); 这不是错误
  • 也分享错误信息。
  • 好的,各位,帖子已如您所愿更新。
  • 试试 this.$data.item 来访问数据。
  • @ThomasKleßen 不幸的是,$data 遇到了同样的错误

标签: javascript vue.js


【解决方案1】:

使用toggle(elementId = 0, type = 'item') {} 而不是toggle: (elementId = 0, type = 'item') => {}
箭头函数将this 分配给其父级的this 范围。
见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Arrow_functions_used_as_methods

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多