Я использую vue. js стиль класса с плагином vue -property-decorator. у меня есть класс с именем Person, как показано ниже:
export default class Person {
fullName: string = '';
id: number = 0;
isSelected: boolean = false;
}
и два компонента: PersonList и PersonSingle, который PersonList показывает список PersonSingles, используя v-for и передавая объект Person;
здесь это PersonSingle:
<template>
<div :class="{selected:isSelected}" @click="select"
style="margin:20px;border:1px solid green;">
<h1>{{fullName}}</h1>
</div>
</template>
<script lang="ts">
import {Vue, Component, Prop} from 'vue-property-decorator';
import Person from '@/store/person';
@Component({})
export default class PersonSingle extends Vue {
@Prop() data?: Person;
fullName: string = '';
isSelected: boolean = false;
id: number = 0;
created(){
if(this.data === null || this.data === undefined) return;
this.fullName = this.data.fullName;
this.isSelected = this.data.isSelected;
this.id = this.data.id;
}
select(){
this.$emit('PersonSelected',this.id);
}
}
</script>
<style>
.selected{
color:red;
background-color: darkgray;
}
</style>
и PersonList:
<template>
<div>
<PersonSingle
v-for="(person,index) in persons"
:key="person.id"
:index="index"
:data="person"
@PersonSelected="onPersonSelected($event)"
></PersonSingle>
</div>
</template>
<script lang="ts">
import {Vue, Component, Prop} from 'vue-property-decorator';
import PersonSingle from '@/components/PersonSingle.vue'
import Person from '@/store/person'
import {ObservableArray} from '@/store/person';
@Component({
components: {PersonSingle}
})
export default class PersonList extends Vue {
persons: Person[] = [] ;
created(){
const p1 = new Person();
p1.fullName = "Mohsen Seylani";
p1.id = 1;
p1.isSelected = true;
const p2 = new Person();
p2.fullName = "Hassan Najrani";
p2.id = 2;
const p3 = new Person();
p3.fullName = "Reza Rad";
p3.id = 3;
const tempArray: Person[] = [];
this.persons.push(p1,p2,p3);
}
onPersonSelected(id: number){
let index = 0;
let tempPerson = new Person();
this.persons.forEach((item,i)=>{
item.isSelected = false;
if(item.id === id){
index = i;
tempPerson = item;
}
});
tempPerson.isSelected = true;
this.$set(this.persons,index,tempPerson);
}
}
</script>
вывод такой, как показано ниже: ![enter image description here](https://i.stack.imgur.com/JFxZP.png)
я хочу, когда пользователь нажимает один из PersonSingle, чтобы этот элемент был выбран, а другие были отменены. как говорят коды, я использовал это. $ set для изменения значения свойства isSelected объекта. но этот код не работает и список не будет перерисован.