【问题标题】:Vue Reactivity when using Typescript classes使用 Typescript 类时的 Vue 反应性
【发布时间】:2020-03-29 14:23:48
【问题描述】:

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

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

该实例化类的任何公共成员都不是响应式的,无论其类型如何。

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

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

【问题讨论】:

    标签: typescript vue.js vue-reactivity


    【解决方案1】:

    如果您将类的实例传递给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;
        }
    };
    
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2021-07-08
      • 2020-01-29
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多