0👍
Shared states should be store in parent component, in this case, only parent component should know what server was selected.
You can change style/class directly from parent, or you can pass a prop like isSelected
to each child component, example parent component:
<template>
<div>
<server
v-for="(server) in servers"
:key="server.id"
:is-selected="server.id == activeServer"
:server="server"
@selected="selectServer(server.id)"
/>
</div>
</template>
<script>
export default {
data() {
return {
servers: [
{
id: 1,
status: 'ok'
},
{
id: 2,
status: 'ok'
},
{
id: 3,
status: 'ng'
},
],
activeServer: null,
}
}
methods: {
selectServer(serverId) {
this.activeServer = serverId
}
}
}
</script>
And child component:
<template>
<li
class="list-group-item"
style="cursor: pointer"
@click="serverSelected"
v-bind:style='{"background-color": isSelected}'>
Server #{{ server.id }} Server status: #{{ server.status }}
</li>
</template>
<script>
export default {
props: ['server', 'isSelected'],
methods: {
serverSelected() {
this.$emit('selected', this.server.id)
}
}
}
</script>
Source:stackexchange.com