安装组件时私有变量不可用

时间:2018-03-07 09:07:40

标签: javascript typescript vue.js

示例:

@Component
export default class MyVueComponent extends Vue {

    private _myVar: string = "not undefined";

    constructor() {
        super();
        console.log(this._myVar);
    }

    mounted() {
        console.log(this._myVar);
    }
}

控制台:

"not undefined"
undefined

我似乎没有找到关键字来正确地解决问题。直觉上它不应该像这样,但很明显我做错了/不理解基本概念。

1 个答案:

答案 0 :(得分:1)

这个的关键是如何调用mounted方法。

构造

如果它作为Vue构造函数的一部分调用,则该变量可以是未定义的。这是一个带有缩减设置的演示,其中_myVar未定义......

class Vue {
    constructor() {
        this.mounted();
    }
}


class MyVueComponent extends Vue {

    private _myVar: string = "not undefined";

    constructor() {
        super();
        console.log(this._myVar);
    }

    mounted() {
        console.log(this._myVar);
    }
}

const x = new MyVueComponent();

这是因为生成的构造函数中的排序,如下所示:

function MyVueComponent() {
    var _this = _super.call(this) || this; // <-- _myVar undefined
    _this._myVar = "not undefined"; // <-- and then it gets defined
    console.log(_this._myVar);
    return _this;
}

事件/范围损失

第二种可能性是,如果事件调用该方法,或者可能丢失范围的另一种情况:

class Vue {
    constructor() {
    }
}


class MyVueComponent extends Vue {

    private _myVar: string = "not undefined";

    constructor() {
        super();
        console.log(this._myVar);
    }

    mounted() {
        console.log(this._myVar);
    }
}

const x = new MyVueComponent();

// Scope Interrupted
window.setTimeout(x.mounted, 20);

在这些情况下,保留范围的箭头功能可以解决问题:

const x = new MyVueComponent();
window.setTimeout(() => x.mounted(), 20);