ネイティブなVueでcomputedとwatchの機能を実装

TypeScriptでVueのcomputedとwatch機能をリファクタリングする手順は次のとおりです。

  1. 計算されました
  2. まず、ゲッターのバックアップを作成します。
class Computed {
getters: Record<string, () => any> = {}
constructor(data: Record<string, any>) {
// 遍历 data 对象的属性
for (const key in data) {
// 如果属性值是函数,则将其添加到 getters 中
if (typeof data[key] === 'function') {
this.getters[key] = data[key];
}
}
}
}
  1. みる
  2. watchers
class Watch {
watchers: Record<string, (newValue: any, oldValue: any) => void> = {}
constructor(data: Record<string, any>) {
// 遍历 data 对象的属性
for (const key in data) {
// 如果属性值是函数,则将其添加到 watchers 中
if (typeof data[key] === 'function') {
this.watchers[key] = data[key];
}
}
}
}
  1. ビュー
  2. 計算された
  3. 見る
  4. ネイティブで日本語に言い換えます
class Vue {
computed: Computed;
watch: Watch;
constructor(data: Record<string, any>) {
this.computed = new Computed(data);
this.watch = new Watch(data);
}
}
  1. データオブジェクトを渡して計算されるプロパティと観察されるプロパティにアクセスするサンプルを作成します。
const data = {
count: 0,
doubleCount() {
return this.count * 2;
},
watchCount(newValue: any, oldValue: any) {
console.log(`count changed from ${oldValue} to ${newValue}`);
},
};
const vm = new Vue(data);
console.log(vm.computed.getters.doubleCount()); // 输出: 0
vm.watch.watchers.watchCount(1, 0); // 输出: count changed from 0 to 1

上記のステップに従うことで Vue の computed と watch 機能を TypeScript でリファクタリングできます。

bannerAds