【问题标题】:Styling active item in a <b-list-group> (vue.js)在 <b-list-group> (vue.js) 中设置活动项目的样式
【发布时间】:2022-01-01 17:44:01
【问题描述】:

我对 vue.js 还很陌生,目前正在尝试为列表组的特定项目设置样式。我的应用程序分为主导航、侧边菜单和主要内容部分。单击列表组中的项目应该会突出显示单击的项目并更改主要内容。更改内容效果很好,但我正在努力为列表中的项目设置样式。侧边菜单的组件代码如下所示:

<div id="app">
<div>
    <b-list-group>
        <b-list-group-item 
            v-for="item in this.items" 
            v-on:click="selectItem(item.id)"
            :key="item.id" 
            class="item-selection">
                {{item.title}}
        </b-list-group-item>
    </b-list-group>
</div>
</div>

我从中获取项目的“项目”数组存储在 vuex 存储中,并且访问一切正常。我知道您可以将列表组的单个项目设置为“活动”,但是由于我使用 for-each 构造从数组中获取项目,因此我无法弄清楚在我的情况下如何做到这一点。我尝试使用这样的条件类:

v-bind:class="{'item-selection':true, 'active-item':(item.id === this.currentItem)}"

但这只会导致启动应用程序时项目甚至不显示。 ('currentItem' 是当前选中项的索引,它也存储在 vuex 存储中)。 'item-selection' 类仅用于项目的一般样式(在添加条件之前工作正常),因此硬编码为 true,即我想用于突出显示的 'active-item' 类。

大家有什么建议吗?我错过了什么(微不足道的)吗?

编辑:

javascript:

new Vue({
  el: '#app',
  data: {
    items :[
      {id: 0,
       title: 'first item'},
       {id: 1,
       title: 'second item'},
       {id: 2,
       title: 'third item'}
    ],
    currentItem : 0
  },
  methods: {
    selectItem(id){
      currentItem = id;
    }
  }
})

css:

.item-selection:hover{
  color: black;
  cursor: pointer;
  background: #ebebeb;
}

.item-selection{
  background-color: #ffffff;
}

.active-item{
  background-color: #444444;
}

【问题讨论】:

  • 什么是点击功能? @click="????"。
  • 您好,您介意创建一个minimal reproducible example,以便我们更轻松地检查并为您提供建议吗?
  • @Erenn 点击项目时调用的函数如下 selectContent(item){ this.$store.commit('setCurrentItem', item);它基本上只是更改存储在 vuex 存储中的当前选定项。它用于更改工作正常的主要内容。
  • @HuyPham 我试图将其分解为一个最小的示例并对其进行编辑。谢谢你的建议!

标签: javascript html vue.js vuejs2 vuex


【解决方案1】:
v-bind:class="{'item-selection':true, 'active-item': item.id === currentItem}"


methods: {
  selectItem(id){
    this.currentItem = id;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2012-12-19
    • 2020-03-18
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多