I'm using vuejs with typescript and vue-class-component. I'm trying to create a custom component with reactive data.
Here is my code:
<template>
<div>
<input v-model="data.name" placeholder="Name">
<input v-model="data.value" placeholder="Value">
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
interface Model {
name: string;
value: number;
}
@Component
export default class ClubVue extends Vue {
private data: Model;
public mounted() {
this.data = {...this.$store.getters.data};
}
}
</script>
In this first version, I've got this error :
Property or method "data" is not defined on the instance but referenced during render
That's normal, as said in vue-class-component page, undefined data won't be reflective. I need to initialize data to null. Furthermore, i get this typescript error:
Property 'data' has no initializer and is not definitely assigned in the constructor
So I want to do this:
private data: Model = null;
But I get this typescript error:
Type 'null' is not assignable to type 'Model'.
I don't wan't to change the data type to Model | null
because I would have to check if data is null everywhere I will use it, and I know that data will never be null.
private data!: Model;
Does not work either because data will be undefined and so won't be reactive.
I don't want to turn off typescript checks because they are useful for other parts of code.
Is there a proper way to initialize data here?
typeof(this._data) === 'undefined'
is redundant,this._data === undefined
is more readable but unnecessary too because it can be either undefined or an object in this snippet. As forprivate _data: Model | undefined
, it can be shortened toprivate _data?: Model
. – Plagiarism