美文网首页
vue 使用函数给导航添加选中效果样式

vue 使用函数给导航添加选中效果样式

作者: 5cc9c8608284 | 来源:发表于2022-03-18 11:01 被阅读0次

需求:
自己写的导航栏,当点击导航的某一项的时候,图片和文字都要变成蓝色,但是这个图片不是icon或者svg,是ui小姐姐设计的png图片,所以采用函数的形式动态的返回图片路径,以达到想要要的效果,具体实现代码如下,二级导航没有贴出来,实现思路是一样的.
结构:

         <div class="firstnav">
            <div
              class="item"
              v-for="(item, index) in topNavList"
              :style="getLeftSelected(item)"
              :key="index"
            >
              <img
                style="margin-right: 12px; width: 14px"
                :src="getLeftImage(item, index)"
                alt=""
              />
              <p>{{ item.title }}</p>
            </div>
        </div>

样式:

.firstnav {
  box-shadow: 1px 0px 0px 0px #ededed;
  width: 260px;
  height: 100vh;
    .item {
      height: 50px;
      display: flex;
      align-items: center;
      box-shadow: 1px 0px 0px 0px #ededed;
      font-size: 14px;
      padding: 0 20px;
      //   opacity: 0.09;
    }
    .item.selected,
    .item:hover {
      background: #ecf5ff;
      box-shadow: 1px 0px 0px 0px #ededed;
      color: #2a95ff;
  }
}

逻辑:

export default{
   data(){
      return {
           topNavSelected: undefined, //被选中的一级导航的id值
}
},
  methods:{
    // 通过函数给导航栏添加选中状态的样式
    getLeftSelected(item) {
      // console.log(item, "item");
      if (this.topNavSelected == item.itemId) {
        //如果是被选中的一项,则给他添加背景颜色和字体颜色
        return {
          background: "#ecf5ff",
          color: "#2a95ff",
        };
      }
      if (item.state == 2) {
        return {
          color: "#67C23A",
        };
      }
      return {
        background: "#ecf5ff",
        color: "#2a95ff",
      };
    },


   // 一级导航对应的图片
    getLeftImage(item, index) {
      //获取每级导航栏对应的图标
      if (this.topNavSelected == item.itemId) {
        return require("@/assets/images/score2/left/left" +
          (index + 1) +
          "-blue.png");
      }
      if (item.state == 2) {
        //state=2:所选中的导航下的题目已做完
        return require("@/assets/images/score2/left/left" +
          (index + 1) +
          "-green.png");
      }
      return require("@/assets/images/score2/left/left" + (index + 1) + ".png");
    },
}
}

存放图片的目录结构是这样的:


left.png

相关文章

网友评论

      本文标题:vue 使用函数给导航添加选中效果样式

      本文链接:https://www.haomeiwen.com/subject/jlugdrtx.html