【问题标题】:Vuejs, change a button color in a list when its clickedVuejs,单击时更改列表中的按钮颜色
【发布时间】:2021-06-19 13:55:04
【问题描述】:

我有一个使用对象数组填充的按钮列表:

          <div
            class="form-inline"
            v-for="(genre, index) in genreArray"
            :key="index"
          >
            <button class="btn m-1" type="button" @click="genreButton(genre, index)" 
                :class="[
                  { 'clicked': clicked}
                ]"
            >
              {{ genre.name }}
            </button>
          </div>

数组的格式如下:

genreButton=[{
  id='1234'
  name='buttonOne'
},
//and many more objects with same key and different values
]

我尝试通过向其添加类来更改单击按钮的颜色:

data(){
  return {
    clicked: false  
  }
},
methods:{
  genreButton(genre, index){
    this.clicked = !this.clicked
  }
}

这是 CSS:

.clicked{
  background-color= red;
}

但问题是当我这样做时,所有按钮都会改变颜色。如何更改被点击按钮的颜色?

【问题讨论】:

标签: javascript html css vue.js object


【解决方案1】:

这里,clicked 是一个组件级属性,因此它被其中的所有按钮共享。

一种解决方案是为genreButton 数组的每个按钮设置一个名为clicked 的属性:

genreButton=[
  {
    id:'1234'
    name:'buttonOne'
    clicked: false,
  },
  //...
]

但是,更优雅的方法可能是使用内部 clicked 属性为按钮创建专用组件。

<template>
  <button 
    class="btn m-1" 
    type="button" 
    @click="clicked = !clicked" 
    :class="[ { 'clicked': clicked} ]" >
    {{ genre.name }}
  </button>
</template>

<script>
export default {
  name: 'CustomButton',
  props: {
    genre: Object,
  },
  data: () => ({
    clicked: false,
  })
}
</script>

<style scoped>
.clicked{
  background-color= red;
}
</style>

然后您可以像这样使用您的按钮组件:

<div
  class="form-inline"
  v-for="(genre, index) in genreArray"
  :key="index" >
  <CustomButton :genre="genre" />
  
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 2012-12-06
    • 2016-09-08
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多