vue如何实现列表点击选中(可多选)点击其他取消所有选中状态

2020-07-23  本文已影响0人  _孙小胖
效果展示图 image.png
<ul class="Flex">
    <li>技术特长:</li>
      <li
        v-for="item in listArr"
        :key="item.value"
        @click="liClick(item)"
        :class="{'active':item.show===true}"
      >{{item.name}}</li>
    </ul>
 <p>当前选中项:{{checkArr}}</p>

数据配置及操作

  data() {
    return {
      checkArr: [],//当前点击选中数据
      selectData: ""
      listArr: [
        {
          value: 0,
          show: false,
          count: 0,
          name: "无"
        },
        {
          value: 1,
          show: false,
          count: 1,
          name: "CSS"
        },
        {
          value: 2,
          show: false,
          count: 1,
          name: "HTML"
        },
        {
          value: 3,
          show: false,
          name: "不详",
          count: 0
        }
      ],
    };
  },
  methods: {
    liClick(item) {
      item.show = !item.show;
     //count == 0就是不详或无
      if (item.count == 0) {
        //否定
        if (item.show) {
          this.listArr.forEach(function(c) {
            // 区分不详无
            if (c.value != item.value) {
              c.show = false;
            }
          });
        this.selectData = [item];
          this.checkArr = ""; //当前选中name
          for (var i = 0; i < this.selectData.length; i++) {
            this.checkArr += this.selectData[i].name + "  ";
          }
        } else {
          this.checkArr = [];
        }
      } else {
        // 肯定
        this.checkArr = this.listArr.filter(function(element, index) {
          return element.count != 0 && element.show == true;
        });
     this.checkArr = "";
        for (var i = 0; i < this.selectData.length; i++) {
          this.checkArr += this.selectData[i].name + "  ";
        }
        // 显示状态
        this.listArr.forEach(ele => {
          if (ele.count == 0) {
            ele.show = false;
          }
        });
      }
      console.log(this.checkArr);
    },
  },

样式

.Flex {
  display: flex;
  display: -webkit-box;
  display: -moz-box;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flexbox;
}
ul {
  width: 300px;
}
ul > li:first-child {
  border: 0;
  cursor: progress;
}
ul > li {
  line-height: 50px;
  font-size: 14px;
  border: 1px solid #d7d7d7;
  padding: 0 20px;
  cursor: pointer;
}
ul > .active {
  background: #2dd1fc;
  color: #fff;
}
ul > .cancel {
  background: #fff;
}
ul > li > span {
  color: aquamarine;
}
上一篇下一篇

猜你喜欢

热点阅读