【问题标题】:vue dynamic vlaue based on multiple data基于多个数据的vue动态值
【发布时间】:2020-10-02 23:25:55
【问题描述】:

基于大多数提到单个参数的 vue 文档, 我使用了 v-on:mouseover 并根据每个项目的颜色动态控制样式,因为我需要根据每个项目的颜色通过悬停来更改每个项目的颜色,虽然我使用 !important 和样式,但它不会改变

<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`;
    }
}

【问题讨论】:

  • 不要改变 DOM。使用 vue 绑定样式。 vuejs.org/v2/guide/class-and-style.html
  • 正如我所说,我尝试了所有单一数据样式,我需要将不同的样式作为颜色传递给 css 或样式

标签: vue.js vue-directives vue-styleguidist


【解决方案1】:

另一种不使用 mouseleave 和 mouseover 的方法,只使用 CSS:

使用 :style 为每个列表项从其数据定义中应用主颜色。还要在父元素class="list" 上添加带有悬停效果颜色的类。最后是class="list-item",它只在悬停时从父级继承颜色。因此颜色 red 仅在悬停时继承:

<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>

实例:

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">

【讨论】:

  • 感谢您的回复,但正如我所提到的,主要问题是悬停时的颜色不同,初始颜色和基本颜色相同,例如红色,但是悬停时它会根据您的方式更改为它的颜色,所有项目都有相同的悬停颜色(红色)
  • 你的意思是当你将鼠标悬停在每个项目上时你需要不同的颜色?例如,主要颜色是红色,当悬停在第一个项目上时,它变成灰色,这是?
  • 完美,我将:style="{ color: item.color }" 移动到&lt;li&gt; and only used .list-item:hover {color: inherit !important;},这是一个聪明的解决方案
  • 是的,我前段时间也学到了这个技巧,在悬停时从父级继承颜色。为此,它完美地工作!
猜你喜欢
  • 1970-01-01
  • 2016-05-20
  • 2023-02-13
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
相关资源
最近更新 更多