首页 > 解决方案 > 基于 Vue2 类的数据属性不是反应式的

问题描述

我在基于 vue2 类的组件中使用打字稿。使用自定义类型 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 道具,但仍然无法正常工作。任何解决方案或建议可能会有所帮助!

标签: vuejs2reactivevue-class-components

解决方案


VueJS 无法检测对象中的属性添加或删除。而且由于0运行时示例数据中不存在密钥,因此稍后添加它不会产生您期望的结果。

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

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

推荐阅读