使用 Typescript 时的 Vue 反应性 类

Vue Reactivity when using Typescript classes

我有一个 Vue 2.6.10 应用程序 运行 Typescript 3.6.3.

我声明了一个 Typescript class 来为应用程序执行一些标准功能。我有一个插件可以将 class 的实例分配给 Vue 的原型。

实例化的 class 的 public 成员无论其类型如何都是反应式的。

我提炼了这个例子 https://codepen.io/ColdToast/pen/KKwwjwY

Class

class Module {
    public _person = null;

    constructor() {}

    get person() {
        return this._person;
    }

    set person(val) {
        this._person = val;
    }

    fetchData() {
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve('Person data'), 1000);
        });
    }
}

插件和应用程序

const MyPlugin = {
    install(Vue) {
        Object.defineProperties(Vue.prototype, {
            $module: { value: new Module() }
        });
    }
};

const App = {
    name: 'App',

    template: `<p>Hello {{ name }}</p>`,

    computed: {
        // Expect to resolve to 'Person data'
        name() {
            return this.$module.person;
        }
    },

    async created() {
        // I expect `data` to be 'Person data'
        const data = await this.$module.fetchData();

        // Properly logs 'Person data'
        console.log(data);

        this.$module.person = data;
    }
};

如果您将 class 的实例传递给 Vuedata,那么一切都会按预期进行。它并不理想,但有以下效果:

const App = {
    name: 'App',

    template: `<p>Hello {{ name }}</p>`,

    computed: {
        // Expect to resolve to 'Person data'
        name() {
            return this.$module.person;
        }
    },

    data() {
        return {
            module: this.$module
        };
    },

    async created() {
        const data = await this.$module.fetchData();

        this.$module.person = data;
    }
};