vue之实现菜单栏选中、不选中时的样式和相应请求处理

对于项目实战的初中级前端人员来说,封装自己菜单栏组件是很有必要的,因为这可以提高开发效率,代码复用率较高。让自己每次在编写页面的时候不再一个字母一个字母的敲。

好,今天我们就来学习下,怎么去封装自己的菜单栏组件,而且点击时显示被选中的样式,并请求相应的数据或做出相应的逻辑处理。

首先按照惯例,先来看看菜单栏蓝图:

这里只是简单的菜单栏,能满足基本的需求,如果有强迫症的童鞋可以线下去优化和美化。

现在正式看看用代码怎么实现:

HTML部分:

<div class="deadline">
   <p>操作时间:</p>
   <ul class="deadlineOption" @click="active_operate_time_index($event)">
     <li :class="active_id == 'week' ? 'addClass' : ''" id="week">本周</li>
     <li :class="active_id == 'month' ? 'addClass' : ''" id="month">本月</li>
     <li :class="active_id == 'year' ? 'addClass' : ''" id="year">今年</li>
     <li :class="active_id == 'customize' ? 'addClass' : ''" id="customize">自定义</li>
   </ul>
   <ul class="getDate" v-show="active_id == 'customize' ? true : false">
     <li>起始:<input type="date" value="startTime" class="customizeDate" ref="startTime" /></li>
     <li>结束:<input type="date" value="endTime" class="customizeDate" ref="endTime" /></li>
   </ul>
</div>

CSS部分:

​
  .deadline{
    width:600px;
    height: 80px;
  }

  .deadlineOption.getDate{
    width: 50%;
    height: 80px;
    text-align: center;
    float: left;
  }

  .deadline p{
    float: left;
    line-height: 80px;
  }  

  .deadlineOption li,.getDate li{
    font-size: 12px;
    padding: 0 10px;
    height: 40px;
    line-height: 40px;
    float: left;
    margin: 20px 0;
  }

  .deadlineOption li:hover{
    cursor: pointer;
  }

​  .addClass{
    background: #1ab394;
    color: white;
  }

JS部分:

     // 选择菜单栏跳转或逻辑处理
      active_operate_time_index: function(event){
        event = window.event || event || e;
        var target = event.target || window.event.srcElement;
        // 下面是获取属性id,因为每个菜单项都有一个标识id,那么可以根据id来做不同的处理
        var id = target.getAttribute('id');
        this.active_id = id;
        this.handleMenu(this.active_id);
      },

      // 具体做出处理的函数
      handleMenu: function (active_id){
        // 这里也可以用switch语句,看个人喜欢
        if(active_id == 'week'){
          // handle week codes go here
        }else if(active_id == 'month'){
          // handle month codes go here
        }else if(active_id == 'year'){
          // handle year codes go here
        }else {
          // handle customize codes go here
        }
      }

这里只是演示了基本的菜单栏的功能,更加强大的功能可在此基础上进行扩展。

猜你喜欢

转载自blog.csdn.net/Charles_Tian/article/details/81238777