简体   繁体   中英

Vue Reactivity when using Typescript classes

I have a Vue 2.6.10 app running Typescript 3.6.3.

I have a Typescript class declared that performs some standard functions for the application. I have a plugin that assigns the instance of that class to Vue's prototype.

No public member of that instantiated class is reactive regardless of its type.

I distilled the example down 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);
        });
    }
}

Plugin and App

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;
    }
};

If you pass the instance of the class to the data of Vue then everything works as expected. Its not ideal but the following works:

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;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM