Vuejs2 基于Vue2类的数据属性不是被动的

Vuejs2 基于Vue2类的数据属性不是被动的,vuejs2,reactive,vue-class-components,Vuejs2,Reactive,Vue Class Components,我在基于vue2类的组件中使用了typescript。使用自定义类型KeyValuePair时,组件中的sampleData属性不是被动的 export type KeyValuePair<T> = { [key in string | number]: T; }; <template> <div> <!-- remains empty even after sampleData is updated ! --> {{ sampleData

我在基于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>
导出类型KeyValuePair={
[输入字符串|编号]:T;
};
{{sampleData}}
@组件()
导出默认类示例扩展Vue{
sampleData:KeyValuePair={};
//假设它不知怎么被调用了
采样方法(){
this.sampleData['0']='sample data';
}
}
还尝试从getter访问sampleData道具,但仍然不起作用。 任何解决方案或建议都可能有帮助

。由于
0
键在运行时不存在于示例数据中,因此稍后添加它将不会产生预期的结果

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

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

它也在工作,
const key=0;this.sampleData={……this.sampleData,[key]:'sample data'}