在正常的js中。我們?nèi)绻獙?shí)現(xiàn)點(diǎn)擊選中active然后其他取消的效果,我們可以定義一個(gè)類,當(dāng)點(diǎn)擊的時(shí)候給給多有的dom取消active的類,給當(dāng)前元素加上這個(gè)類名,說(shuō)的很啰嗦,直接來(lái)看代碼說(shuō)話吧(表示樓主用的是jq):
<style> * { margin: 0; padding: 0; } li { list-style: none; width: 100px; margin-top: 10px; border: 1px solid red; } li:active { cursor: pointer; } .active { background-color: aqua; } </style> <script src="http://g.ydbcdn.com/jquery/latest/jquery.min.js"></script> </head> <body> <ul> <li>this is pne</li> <li>this is two</li> <li>this is three</li> </ul> </body> <script> $(() => { $("li").click((e) => { $("li").removeClass("active"); $(e.target).addClass("active"); }) }) </script>
效果如下圖所示:
但是在vue里面,是不提倡進(jìn)行dom操作的,如果非進(jìn)行dom的話,vue2.0里面有一個(gè)ref的屬性,是可以達(dá)到dom的效果的。那么接下來(lái)我們不接住dom來(lái)進(jìn)行操作:
由于習(xí)慣了webpack和vue-cli腳手架,所以樓主所有vue的代碼都是放在webpack的腳手架當(dāng)中進(jìn)行,還使用了pug和scss的預(yù)處理器,vue的代碼如下:
<template lang="pug"> ul li(v-for="(item,index) in classArr", @click="result(index)", :class="resultNum === index?'active':''") this is {{item}} </template> <style lang="scss"> li { list-style: none; width: 100px; margin-top: 10px; border: 1px solid red; &:hover { cursor: pointer; } } .active{ background-color: aqua; } </style> <script> export default{ data(){ return { classArr: ["one", "two", "three"], num:"", } }, methods: { result(index){ this.num = index; } }, computed:{ resultNum(){ return this.num; } } } </script>
思路如下:
這段代碼使用的是index這個(gè)關(guān)鍵字,還使用了computed這個(gè)計(jì)算屬性,當(dāng)當(dāng)前的index索引與點(diǎn)擊的當(dāng)前元素的下標(biāo)相同的時(shí)候,便會(huì)觸發(fā)active這個(gè)類名。說(shuō)的很簡(jiǎn)練,不懂的可以加博主一起探討
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請(qǐng)關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
Vue-cropper對(duì)圖片進(jìn)行裁剪
使用Element-UI Table實(shí)現(xiàn)拖拽功能
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com