vue3 vite setup 路由切换按钮的选中状态

275 阅读1分钟

1.如何选中

<template>
  <div id="view">
    <div id="router_btn">
      <router-link to="/page7_page1" class="my_router_link" >
        <div id="btn_position" class="breathing-circle" :class="{ 'selected': currentPath === '/page7_page1' }">实时</div>
      </router-link>
      <router-link to="/page7_page2" class="my_router_link">
        <div id="btn_position2" class="breathing-circle"  :class="{ 'selected': currentPath === '/page7_page2' }">回放</div>
      </router-link>
    </div>
    <router-view id="router_view" />
  </div>
</template>

<script setup>
import { onMounted, watch, ref } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const currentPath = ref(route.path);

onMounted(() => {
  watch(() => route.path, (newPath, oldPath) => {
    currentPath.value = newPath;
  });
});

</script>

<style scoped lang="less">
#view {
  width: 100vw;
  height: 89vh;
  margin-top: 11vh;
  display: flex;

  #router_btn {
    width: 5vw;
    height: 89vh;

    .my_router_link {
      /* 圆形按钮样式 */
      .breathing-circle {
        position: relative;
        width: 4vw;
        height: 4vw;
        text-align: center;
        line-height: 4vw;
        border: 5px solid transparent; /* 圆圈一条线,透明背景 */
        border-radius: 50%;
        overflow: hidden;
        animation: breathe 1.5s infinite alternate; /* 颜色呼吸灯效果,2秒一次,交替进行 */
      }

      /* 动画关键帧 */
      @keyframes breathe {
        0% {
          border-color: #4CAF50;
        }
        100% {
          border-color: #409eaf;
        }
      }

      .breathing-circle:hover {
        border: 4px solid transparent; /* 圆圈一条线,透明背景 */
      }

      #btn_position {
        top: 25vh;
      }
      #btn_position2 {
        top: 26vh;
      }

      .selected {
        background-color: blue;
      }

    }
  }

}
</style>

监听路由的变化,过去新路由的地址。在样式位置动态判断地址来决定是否添加该选中样式。这样,可以将当前路由选中的页面对应的按钮变成选中状态