Home > Back-end >  How to style the components of v-for rendering
How to style the components of v-for rendering

Time:08-21

I'm making a custom component called SelectorGroup in Vue2.When I clicked an item in SelectorGroup,the background of the area where this item is located will change,just like this,did you see the SelectorGroup [Popular,Name,New]?
I can use native DOM operations to solve this queston,but I think it's not graceful.My code like this:

<template>
  <div id="container" ref="container">
     <div v-for="(name,index) in group" :key="index"  @click="choose($event,index)">
        {{name}}
     </div>
  </div>
</template>
<script>
    export default {
    name:'SelectorGroup',
    data() {
        return {
            choosedItem:this.group[0]
        }
    },
    props:{
        //like ['a','b','c']
        group:Array
    },
    methods: {
        choose(event,index){
            const items = Array.from(this.$refs.container.children)
            items.forEach((item)=>{
                if (item.classList.value.search('active')!== -1) {
                    item.classList.remove('active')
                }
            })
            this.choosedItem = this.group[index]
            event.target.classList.add('active')
        }
    },
   
}
</script>
<style scoped>
#container{
    --m-radius:4px;
    display: inline-block;
    overflow: hidden;
}

.item{
    width: fit-content;
    height: 30px;
    padding: 0 5px;
    border: 1px solid black;
    border-right: 0;
    float: left;
    font-size: 16px;
    line-height: 30px;
    cursor: pointer;
}

.item:last-child{
    border-right: 1px solid black;
    border-top-right-radius: var(--m-radius);
    border-bottom-right-radius: var(--m-radius);
}

.item:first-child{
    border-top-left-radius: var(--m-radius);
    border-bottom-left-radius: var(--m-radius);
}

.active{
    background-color: green;
}
</style>

In choose method, we can see that I use some DOM operations to remove the 'active' class which styled previous choosed item,I think my way is not graceful,is there a way to solve this question not by native dom operations?

CodePudding user response:

Just use class/style binding

<script>
    export default {
    name:'SelectorGroup',
    data() {
        return {
            activeItemIndex: 0
        }
    },
    props:{
        //like ['a','b','c']
        group:Array
    },  
}
</script>
<template>
  <div>
     <div v-for="(name,index) in group" :key="index" : @click="activeItemIndex = index">
        {{name}}
     </div>
  </div>
</template>
  • Related