点击选中,再次点击取消

177 阅读1分钟

image.png

业务需求

点击卡片选中,再次点击取消。

代码实现:

getCard(item) {
    const index = this.selectIds.indexOf(item.id)
    index >= 0 ? this.selectIds.splice(index, 1) : this.selectIds.push(item.id)
}

selectIds是data中定义的用来存储被选中的卡片的id的数组。

如果可以在selectIds中找到当前卡片的id,就将其删除;找不到,就将其push进去这个数组。

关于点击之后变色

image.png

image.png

<div :class="{ chooseColor: chooseId(item.id) === 1 }"></div>

computed:{
    // 看selectIds里面有没有选中卡片的id,有,就添加颜色样式;没有,就取消颜色样式
    chooseId() {
      return function (id) {
        return this.selectIds.indexOf(id) != -1 ? 1 : 0
      };
    },
}

.chooseColor {
  border: 2px solid #59cbcd !important;
}

这里有个点,就是计算属性computed也是可以传递参数的,只不过要以闭包的形式来接收。