vue dynamic vlaue based on multiple data

67 Views Asked by At

based on most of vue docs that have mentioned to single parameter, I used the v-on:mouseover and leave to control style dynamically based on each item color because i need to change each item color by hover based on its color and although I used !important with styles, it doesn't change

<li v-for="item in items" v-bind:key="item.id">
    <a class="my-link"
        v-on:mouseleave="mouseLeave(item)"
        v-on:mouseover="mouseOver(item)">

        {{ item.title }}
    </a>
</li>

data() {
    return {
        items: [
            {
                id: 1,
                title: "one",
                color: "#ccc"
            },
            {
                id: 2,
                title: "two",
                color: "#000"
            },
            {
                id: 3,
                title: "three",
                color: "#c7c7c7"
            }
        ]
     }
},
methods: {
    mouseOver: function(item){
        this.$el.children[0].style.color = 'red !important';
    },
    mouseLeave: function(item){
        this.$el.children[0].style.color = `${item.color} !important`;
    }
}
1

There are 1 best solutions below

4
On

Another approach without using mouseleave and mouseover, only CSS:

Apply the main color with :style for each list item from its data definition. Also add class on the parent element class="list" with the color for hover effect. And finally class="list-item" which inherits color from the parent on hover only. Thus color red is inherit on hover only:

<li v-for="item in items" v-bind:key="item.id" class="list" :style="{ color: item.color }">
    <a class="list-item">
        {{ item.title }}
    </a>
</li>
<style scopped>
.list-item {
  color: red;
}
.list-item:hover {
  color: inherit !important;
}
</style>

Live example:

new Vue({
  el: '#app',
  data: {
       items: [
        {
          id: 1,
          title: "one",
          color: "red",
        },
        {
          id: 2,
          title: "two",
          color: "green",
        },
        {
          id: 3,
          title: "three",
          color: "blue",
        }
      ]},
  template: `
   <div>
    <li v-for="item in items" v-bind:key="item.id" class="list" :style="{ color: item.color }">
      <a class="my-link list-item">
        {{ item.title }}
      </a>
    </li>
  </div>`
})
.list-item {
  color: #ccc;
}
.list-item:hover {
  color: inherit !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">