vue3+ts中常用的两个按钮选择事件写法

1. 效果演示

vue3+ts中常用的两个按钮选择事件写法_第1张图片

2.vue3单页面代码演示

<template>
  <div class="btns">
    <div
      v-for="(item, index) in nams"
      @click="btnCol(index)"
      :class="current == index ? 'active' : 'btn'"
    >
      {{ item }}
    </div>
  </div>
  <div class="btns2">
    <div
      :class="item.class"
      v-for="(item, index) in nams2"
      :key="item.name"
      @click="btnCol2(index)"
    >
      {{ item.name }}
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
let nams = ref(["按钮1", "按钮2", "按钮3", "按钮4"]);
let nams2 = ref([
  { name: "按钮1", class: "btn3" },
  { name: "按钮2", class: "btn3" },
  { name: "按钮3", class: "btn3" },
  { name: "按钮4", class: "btn3" },
]);
let current = ref(5);
let current2 = ref(true);

let btnCol = function (index) {
  current.value = index;
  console.log("输出:", current);
};
let btnCol2 = function (index) {
  if (nams2.value[index].class == "btn3") {
    nams2.value[index].class = "active";
  } else {
    nams2.value[index].class = "btn3";
  }
};
</script>

<style scoped lang="scss">
.btns {
  position: absolute;
  left: 50%;
  top: 40%;
  transform: translateX(-50%);
  width: 600px;
  height: 80px;
  border: 1px solid red;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .btn {
    height: 40px;
    width: 100px;
    background: gainsboro;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
    color: black;
    user-select: none;
  }
}
.active {
  background: red;
  height: 40px;
  width: 100px;
  text-align: center;
  line-height: 40px;
  cursor: pointer;
  color: black;
  user-select: none;
}
.btns2 {
  position: absolute;
  left: 50%;
  top: 60%;
  transform: translateX(-50%);
  width: 600px;
  height: 80px;
  border: 1px solid red;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .btn3 {
    height: 40px;
    width: 100px;
    background: gainsboro;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
    color: black;
    user-select: none;
  }
}
</style>

你可能感兴趣的:(vue3,vue.js,前端,javascript)