I have a tree-view component:
<template>
<li :style="{'margin-left': `${depth * 20}px` ,'background-color': `${col}`}" @click="toggle(e); getEl($event)" :title="tree.name">{{tree.name}} </li>
<ul v-show="isOpen" v-if="isFolder" >
<TreeView :tree="chld" v-for="(chld, inx) in tree.children" :key="inx" :depth="depth 1"></TreeView>
</ul>
</template>
my not working script:
getEl(e){
this.col = 'blue'
//how turn previous item`s color back?
return this.tree.id
},
I just want to toggle the item's color, which I choosed, that is when I click an item(im my code this item has @click event) I want to this item change its color to another, but its huge problem to me to turn back previous item to initial color. I
ve struggled many hours on it
CodePudding user response:
As per your requirement, You have to add default color initially to your every tree object and then on click you can perform toggle.
Live Demo :
new Vue({
el: '#app',
data: {
trees: [{
name: 'Tree 1'
}, {
name: 'Tree 2'
}, {
name: 'Tree 3'
}, {
name: 'Tree 4'
}],
defaultColor: 'green'
},
mounted() {
this.trees = this.trees.map(obj => {
obj.color = this.defaultColor;
return obj;
});
},
methods: {
getEl(index) {
const changedColor = 'blue';
this.trees = this.trees.map((obj, i) => {
obj.color = (i === index) ? changedColor : this.defaultColor;
return obj;
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<li v-for="(tree, index) in trees" :key="index" :style="{'background-color': `${tree.color}`}" @click="getEl(index)">{{tree.name}} </li>
</div>