I am fairly new to using Vue and completely unfamiliar with TypeScript. I am trying to pass an array of TaskSolution objects (TaskSolution being a custom type) as a property to a component, then delete some TaskSolution objects from the array and have the interface updated accordingly.
Below is the code where I attempted to achieve this:
//TaskSolution.ts
interface TaskSolution {
task : string,
solution: string,
};
export type { TaskSolution };
Another file:
//ProvideArrayTest.vue
<script lang="ts">
import { defineComponent } from 'vue';
import UseArrayTest from "./UseArrayTest.vue";
import type { TaskSolution } from "./../types/TaskSolution.ts";
export default defineComponent({
components : { UseArrayTest }
});
</script>
<template>
<h1>ProvideArrayTest</h1>
<UseArrayTest :sentences="[ { task: 'not smart', solution: 'stupid' }, { task: 'not good', solution: 'bad' }]" />
</template>
<style scoped>
</style>
Another file:
//UseArrayTest.vue
<script lang="ts">
import { ref, defineComponent } from 'vue';
import type { PropType } from "vue";
import type { TaskSolution } from "./../types/TaskSolution.ts";
export default defineComponent({
// type inference enabled
props: {
sentences : {
required: true,
type: Array as PropType<TaskSolution[]>
},
},
setup(props) {
const sentences2 = ref<TaskSolution[]>(props.sentences);
return { sentences2 };
},
methods : {
deleteSentence(i: number, sentence : TaskSolution) {
console.log("Delete is executed!");
if(i==1){
this.sentences = this.sentences.filter( (item: TaskSolution) => item !== sentence );
}
else if(i==2){
this.sentences2 = this.sentences2.filter( (item: TaskSolution) => item !== sentence );
}
}
}
})
</script>
<template>
<h1>sentences array</h1>
<ul>
<li v-for="sentence in sentences">
Task: {{ sentence.task }} Solution: {{ sentence.solution }} <button @click="deleteSentence(1,sentence)">Delete</button>
</li>
</ul>
<h1>sentences2 array</h1>
<ul>
<li v-for="sentence in sentences2">
Task: {{ sentence.task }} Solution: {{ sentence.solution }} <button @click="deleteSentence(2,sentence)">Delete</button>
</li>
</ul>
</template>
<style scoped>
</style>
After running npm run dev
, the task and solution are displayed correctly for sentences but I am unable to delete anything. Sentences2, however, works flawlessly.
Running npm run build
results in the following errors:
src/components/UseArrayTest.vue:24:18 - error TS2540: Cannot assign to 'sentences' because it is a read-only property.
24 this.sentences = this.sentences.filter( (item: TaskSolution) => item !== sentence ); //Can't assign to read-only property
Is there a way to directly modify the sentences property and update the interface without having to initially copy sentences into sentences2?