Vue 一个完整的 li 的点击选择 和 默认选中

3,302 阅读1分钟

不管是 li 标签 还是 p 标签,同理都是一样的。

<div class="choose-bank">
    <ul>
        <li v-for="(item, index) in chooseBankFilter"
            @click="chooseBank($event, index, item.name)"
            :key="index"
            :class="{ 'choose-bank-selected': chooseBankFlag == index }">
            
            <img src="('/images/bank-logo-map/' + item.name + '.png')" />
            <span>{{item.name}}</span>
            <i></i>
        </li>
    </ul>
</div>

//定义模拟数据
const chooseBankData = [{
    name: '中国银行1',
    number: '6221 2345',
    type: '储蓄卡'
},{
    name: '中国银行2',
    number: '6221 2345',
    type: '储蓄卡'
},{
    name: '中国银行3',
    number: '6221 2345',
    type: '储蓄卡'
},{
    name: '中国银行4',
    number: '6221 2345',
    type: '储蓄卡'
},{
    name: '中国银行5',
    number: '6221 2345',
    type: '储蓄卡'
}]

export default {
    data(){
        return {
            chooseBankData,  //选择银行 - 模拟数据
            chooseBankLimit: 4,  //默认显示4个银行
            chooseBankIcon: `caret-down`,  //选择银行,向下箭头
            chooseBankFlag: 0,    //选择银行的标识
        }
    },
    computed: {
        //选择银行
        chooseBankFilter() {  //截取 4 个银行
            return this.chooseBankData.slice(0, this.chooseBankLimit);
        }
    },
    methods: {
        //选择银行
        chooseBank (e, index, name) {
            //console.log(index)
            this.chooseBankFlag = index
            
            console.log(name)
        }
    }
}

<style scoped lang="less">
    /* 选择银行 */
    .choose-bank ul li {
        width: 158px;
        height: 34px;
        line-height: 34px;
        float:left;
        border:1px solid #cccccc;
        margin-right: 12px;
        margin-bottom: 16px;
        overflow: hidden;
        cursor: pointer;
        position: relative;
        img {
            width: 18px;
            height: 18px;
            margin-left: 10px;
            margin-right: 5px;
            position: relative;
            top: -2px;
        }
    }
    
    /* 选择银行 - 选中状态 */
    .choose-bank ul li.choose-bank-selected {
        border:1px solid #fe9039 !important;
    }
    .choose-bank ul li.choose-bank-selected > i {
        display: block;
        width: 18px;
        height: 18px;
        background: url(/images/choose-bank-selected.png) no-repeat;
        position: absolute;
        bottom:0;
        right:0;
    }
</style>