首页 > 其他分享 >js 数组删除与这条数据相关的所有数据

js 数组删除与这条数据相关的所有数据

时间:2022-11-23 18:00:32浏览次数:43  
标签:name 父级 pid id item 数组 js 数据 children

在开发过程中,后台同事给出的树状数据是列表形式的数据。

当要删除此条数据时,需要删除掉此数据下所有的子级数据。

效果图如下:

 

删除id为11后的数据:

 

 具体代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./vue.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <title>Document</title>
</head>


<body>

    <div id="app">
        <ul>
            <li v-for="item in listData" :key="item.id" @click="deleteItem(item.id)">id是{{item.id}}---pid是{{item.pid}}</li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            listData: [{
                name: '父级1',
                id: '1',
                pid: ''
            }, {
                name: '父级11',
                id: '11',
                pid: '1'
            }, {
                name: '父级12',
                id: '12',
                pid: '1'
            }, {
                name: '父级13',
                id: '13',
                pid: '1'
            }, {
                name: '父级111',
                id: '111',
                pid: '11'
            }, {
                name: '子级1111',
                id: '1111',
                pid: '111'
            }, {
                name: '子级1112',
                id: '1112',
                pid: '111'
            }, {
                name: '父级112',
                id: '112',
                pid: '11'
            }],
            children: {}
        },
        mounted: function() {
            this.updateData()
        },
        methods: {
            deleteItem(id) {
                if (this.children[id]) {
                    this.children[id].forEach(this.deleteItem)
                }
                var index = this.listData.findIndex(i => i.id === id);
                if (index >= 0)
                    this.listData.splice(index, 1);
            },
            updateData() {
                var children = {};
                this.listData.forEach(function(item) {
                    if (item.pid)
                        children[item.pid] = (children[item.pid] || []).concat(item.id);
                });
                this.children = children;
            }
        }
    })
</script>

</html>

 

标签:name,父级,pid,id,item,数组,js,数据,children
From: https://www.cnblogs.com/houBlogs/p/16919288.html

相关文章