【问题标题】:Vue2 class based data property is not reactive基于 Vue2 类的数据属性不是反应式的
【发布时间】:2021-08-14 12:07:18
【问题描述】:

我在基于 vue2 类的组件中使用 typescript。使用自定义类型 KeyValuePair 时,sampleData 属性在组件中不是响应式的。

export type KeyValuePair<T> = {
  [key in string | number]: T;
};

<template>
<div>
<!-- remains empty even after sampleData is updated ! -->
 {{ sampleData }} 
</div> 
<template>

<script>
@Component()
export default class Sample extends Vue {

sampleData: KeyValuePair<string> = {}; 

//assume it gets called somehow
sampleMethod() {
   this.sampleData['0'] = 'sample data';
  }
}
</script>

还尝试从 getter 访问 sampleData 道具,但仍然无法正常工作。 任何解决方案或建议都可能会有所帮助!

【问题讨论】:

标签: vuejs2 reactive vue-class-components


【解决方案1】:

VueJS cannot detect property addition or deletion in objects。而且由于 0 键在运行时不会出现在您的示例数据中,因此稍后添加它不会产生您期望的结果。

您需要使用Vue.set 来实现您想要的:

sampleMethod() {
   Vue.set(this.sampleData, '0', 'sample data');
  }
}

【讨论】:

  • 它也可以工作,const key = 0; this.sampleData = { ...this.sampleData, [key]: 'sample data' }
猜你喜欢
  • 1970-01-01
  • 2020-12-21
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
相关资源
最近更新 更多