Search code examples
vuejs2reactivevue-class-components

Vue2 class based data property is not reactive


I was using typescript in a vue2 class based components. sampleData prop is not reactive in a component while using a custom type KeyValuePair.

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>

Also tried to access sampleData prop from a getter but still not working. Any solutions or suggestions might be helpful!


Solution

  • VueJS cannot detect property addition or deletion in objects. And since the 0 key is not present in your sample data at runtime, adding it later will not yield the result you expect.

    You will need to use Vue.set to achieve what you want:

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