我有一个运行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;
}
};
答案 0 :(得分:0)
如果将类的实例传递给data
的{{1}},那么一切都会按预期进行。它不理想,但可以进行以下工作:
Vue