如下面的導航欄,使用vue技術給該導航欄增加鏈接:
js代碼為:
navigation:function(){ new Vue({ el: '#navUl', data: { menuData:{ '個人首頁':'personal-home.html', '人才分析':'personal-analysis.html', '基本信息':'personal-info-base.html', '技能態度':'skill-attitude.html', '參與項目':'involved-project.html', '學習':'learn.html', '考勤':'work-attend.html', '生活福利':'welfare.html' } }, computed:{ curIdx:function(){ var curIdx = 0; $.each(this.menuData,function(k,v){ if(location.pathname.indexOf(v)!=-1){//說明包括(也就是當前頁面) return false; }else{//==-1說明不包括(不是當前頁面) curIdx++; } }); console.log(curIdx); return curIdx; } } }); }
html代碼為:
<ul class="nav-ul" id="navUl"> <template v-for="(link,name,index) in menuData"> <li class="nav-li" v-bind:class="index==curIdx?'curr':''"><a :href="link">{{ name+'--'+index }}</a></li> </template> </ul>
說明:思路是,每一頁都對應着一個index值,舉例來說:當切換到基本信息頁時,index=2,此時如果curIdx也等於2,那么index==curIdx,增加curr類,文字變紅,而頁面跳轉是給文字增加了鏈接,不是點擊事件造成的;
因此切換到個人首頁時,curIdx==0;切換到人才分析頁時,curIdx==1;切換到基本信息頁時,curIdx==2;以此類推;
對於基本信息頁:js文件中,循環this.menuData,首先當前鏈接不包括第一個鏈接personal-home.html的內容,所以location.pathname.indexOf(v)==-1,此時curIdx由0增加為1;
然后第二次循環,當前鏈接不包括第二個鏈接personal-analysis.html的內容,所以location.pathname.indexOf(v)==-1,此時curIdx由1增加為2;
然后第三次循環,當前鏈接包括第三個鏈接personal-info-base.html的內容,所以location.pathname.indexOf(v)!=-1,此時return出false,curIdx==2;
也就是說基本信息頁的curIdx為2;此時index==curIdx,為當前增加curr類名;