基于Vue实现多标签选择器

简介: 基于Vue实现多标签选择器

实现效果

d24.2.png


实现代码

<html lang="en">

<head>
    <title>Document</title>

    <!-- 引入本地组件库 -->
    <link rel="stylesheet" href="static/element-ui/index.css">
    <script src="static/element-ui/vue.js"></script>
    <script src="static/element-ui/index.js"></script>

    <!-- 引入CDN样式 -->
    <!-- <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> -->
    <!-- <script src="https://unpkg.com/element-ui/lib/index.js"></script> -->

    <style>
        .not-active {
            display: inline-block;
            font-size: 12px;
            margin: 5px 8px;
        }
        
        span {
            margin: 0 2px;
        }
    </style>
</head>

<body>

    <div id="app">
        <!-- 待选标签 -->
        <div v-for='(category, categoryIndex) in categories' :key="category.id">
            <!-- 分类  -->
            <span class="not-active">{
        {category.name}}:</span>

            <template>
                <span  v-if="category.count"class="not-active" @click="clearCategory(category, categoryIndex)"> 不限</span>
                <my-tag v-else>不限</my-tag>
            </template>

            <!-- 标签  -->
            <template v-for='(child, childIndex) in category.children'>
                <my-tag  v-if="child.active" :closable='true'  @click-child='clickChild(category, categoryIndex, child, childIndex)'>
                    {
        { child.name }}
                </my-tag>
                <span v-else class="not-active" @click='clickChild(category, categoryIndex, child, childIndex)'>{
        { child.name }}</span>
            </template>
        </div>

        <!-- 已选标签 -->
        <div v-if='conditions.length'>
            <span class="not-active" @click="clearCondition">清空已选:<span>
                
            <el-tag
            v-for='(condition, index) in conditions' 
            :key="condition.id"
            type="primary"
            :closable="true"
            size="small"
            :disable-transitions="true"
            @close='removeCondition(condition, index)'
            @click='removeCondition(condition, index)'>
                {
        {condition.name}}
            </el-tag>
        </div>
    </div>

    <script src="./data.js"></script>

    <script>
        // 简单封装一个公用组件
        Vue.component('my-tag', {
            template: "<el-tag v-bind='$attrs' v-on='$listeners' effect='dark' size='small' :disable-transitions='true' @click='clickChild' @close='clickChild'><slot></slot></el-tag>",

            methods: {
                clickChild() {
                    this.$emit("click-child")
                }
            }
        });

        var app = new Vue({
            el: '#app',
            data() {
                return {
                    categories, // 分类标签,可从外部加载配置
                    conditions: [] // 已选条件
                }
            },

            watch: {
                // 监听条件变化,按照请求接口拼装请求参数
                conditions(val){
                    let selectedCondition = {};

                    for(let categorie of this.categories){
                        let selected_list = [];
                        for(let child of categorie.children){
                            if(child.active){
                                selected_list.push(child.name);
                            }
                        }
                        selectedCondition[categorie.name] = selected_list.join("|")
                    }
                    console.log(selectedCondition);
                }
            },

            methods: {
                // 处理标签点击事件,未选中则选中,已选中则取消选中
                clickChild(category, categoryIndex, child, childIndex) {
                    let uid = `${categoryIndex}-${childIndex}`
                    child.uid = uid;
                    console.log(uid)
                    
                    // 取消选择
                    if (child.active === true) {
                        category.count--;
                        child.active = false;
                        this.conditions.forEach((conditionChild, index) => {
                            if (conditionChild.uid === child.uid) {
                                this.conditions.splice(index, 1);
                            }
                        });
                    // 选择
                    } else {
                        category.count++;
                        child.active = true;
                        this.conditions.push(child);
                    }
                },
            
                // 清除已选整个类别标签
                clearCategory(category, categoryIndex) {
                    category.count = 0;
                    
                    // 可选列表均为未选中状态
                    category.children.forEach(child => {
                        child.active = false;
                    })

                    // 清空该类已选元素
                    for (let index = this.conditions.length - 1; index >= 0; index--) {
                        const conditionChild = this.conditions[index];
                        if (conditionChild.uid.startsWith(categoryIndex)) {
                            this.conditions.splice(index, 1);
                        }
                    }
                },
                
                // 移除一个条件
                removeCondition(condition, index) {
                    let categoryIndex = condition.uid.split("-")[0];
                    this.categories[categoryIndex].count --;

                    this.conditions.splice(index, 1)
                    condition.active = false;
                },

                // 清空所有条件
                clearCondition() {
                    for(let i = this.conditions.length-1; i >=0 ; i--){
                        this.removeCondition(this.conditions[i], i);
                    }
                }
            }
        });
    </script>

</body>

</html>

标签筛选的数据格式

data.js

var categories = [{

name: '品牌',
count: 0,
children: [{
name: '联想',
}, {
name: '小米',

}, {
name: '苹果',

}, {
name: '东芝',

}]
}, {
name: 'CPU',
count: 0,
children: [{
name: 'intel i7 8700K',

}, {
name: 'intel i7 7700K',

}, {
name: 'intel i9 9270K',

}, {
name: 'intel i7 8700',

}, {
name: 'AMD 1600X',


}]
}, {
name: '内存',
count: 0,
children: [{
name: '七彩虹8G',

}, {
name: '七彩虹16G',

}, {
name: '金士顿8G',

}, {
name: '金士顿16G',

}]
}, {
name: '显卡',
count: 0,
children: [{
name: 'NVIDIA 1060 8G',

}, {
name: 'NVIDIA 1080Ti 16G',

}, {
name: 'NVIDIA 1080 8G',

}, {
name: 'NVIDIA 1060Ti 16G',

}]
}]


            </div>
目录
相关文章
|
算法 关系型数据库 MySQL
【MySQL系列】Select语句单表查询详解(二)ORDERBY排序
文章目录 一、排序ORDER BY 1.ORDER BY的格式: 2.ORDER BY的作用: 3.ORDER BY的使用: 1️⃣ 按照字段名排序 2️⃣按字段照序号进行排序 3️⃣降序DESC 4️⃣根据多列排序 5️⃣还可以结合搭配函数或者一些查询条件使用。
|
12月前
|
关系型数据库 MySQL 数据库
[MYSQL] MYSQL表的操作
掌握MySQL表的操作是数据库管理的基础,涉及创建、修改、查询、更新和删除等多方面内
255 13
|
测试技术 Python
探索软件测试的深度与广度:从理论到实践
在数字化时代,软件已成为我们生活中不可或缺的一部分。随着技术的不断进步和用户需求的多样化,确保软件质量变得尤为重要。本文将深入浅出地介绍软件测试的核心概念、类型及其在软件开发生命周期中的重要性。我们将通过实际案例,展示如何实施有效的测试策略,并探讨自动化测试的未来趋势,旨在为读者提供一套完整的软件测试知识体系,帮助提升软件质量和开发效率。
|
网络协议 安全 物联网
探索未来网络:从IPv4到IPv6的演变
本文深入探讨了互联网协议从IPv4向IPv6演进的背景、原因及带来的深远影响。随着物联网、5G等技术的发展,IPv4地址枯竭问题愈发严峻,IPv6应运而生,不仅解决了地址短缺,还提升了网络性能和安全性。通过详细阐述两者在地址空间、报文结构、头部格式等方面的差异,文章强调了IPv6在简化数据包处理流程、增强组播支持等方面的优势。同时,指出IPv6过渡面临的挑战,并展望其在未来互联网中的广阔应用前景。
|
存储 消息中间件 运维
友盟+|如何通过阿里云Flink+Paimon实现流式湖仓落地方案
本文主要分享友盟+ U-App 整体的技术架构,以及在实时和离线计算上面的优化方案。
949 2
友盟+|如何通过阿里云Flink+Paimon实现流式湖仓落地方案
|
存储 小程序 数据库
【小程序云开发】30分钟搭建个人相册小程序
本文将通过实战“个人相册小程序”开发,教你如何借助小程序 ·云开发 能力,提升功能开发效率,提升数据隐私保护能力。
1140 0
|
存储 SQL DataWorks
阿里云数据分析常用工具介绍 | 学习笔记
快速学习阿里云数据分析常用工具介绍。
阿里云数据分析常用工具介绍 | 学习笔记
|
Web App开发 前端开发 数据可视化
【性能篇】28 # Canvas、SVG与WebGL在性能上的优势与劣势
【性能篇】28 # Canvas、SVG与WebGL在性能上的优势与劣势
1154 0
【性能篇】28 # Canvas、SVG与WebGL在性能上的优势与劣势
|
网络协议 安全
内网接入外网的几种方式
内网接入外网的几种方式
1237 0