elementui Tree 树形控件增删改查

数据表结构:

前端代码

axios.js

import axios from ‘axios‘;
import Qs from ‘qs‘;
import {Message} from ‘element-ui‘;

axios.defaults.baseURL = "/";
// 设置请求超时时间
axios.defaults.timeout = 30000;

// 设置post请求头
axios.defaults.headers.post[‘Content-Type‘] = ‘application/json;charset=UTF-8‘;

// 请求拦截
axios.interceptors.request.use(config => {
    // 在发送请求之前做些什么 验证token之类的

    return config;
}, error => {
    // 对请求错误做些什么

    Message.error({message: ‘请求超时!‘})
    return Promise.error(error);
})

// 响应拦截
axios.interceptors.response.use(response => {
    // 对响应数据做点什么

    return response;
}, error => {
    // 对响应错误做点什么

    return Promise.reject(error);
});

// 封装get方法和post方法

/**
 * get方法,对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res.data);
            //  Loading.service(true).close();
            //  Message({message: ‘请求成功‘, type: ‘success‘});
        }).catch(err => {
            reject(err.data)
            //  Loading.service(true).close();
            Message({message: ‘加载失败‘, type: ‘error‘});
        })
    });
}

/**
 * post方法,对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(res => {
                resolve(res.data);
                // Loading.service(true).close();
                //  Message({message: ‘请求成功‘, type: ‘success‘});
            })
            .catch(err => {
                reject(err.data)
                // Loading.service(true).close();
                Message({message: ‘加载失败‘, type: ‘error‘});
            })
    });
}

/**
 * post方法,参数序列化
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function qspost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, Qs.stringify(params))
            .then(res => {
                resolve(res.data);
                //  Loading.service(true).close();
                //  Message({message: ‘请求成功‘, type: ‘success‘});
            })
            .catch(err => {
                reject(err.data)
                // Loading.service(true).close();
                Message({message: ‘加载失败‘, type: ‘error‘});
            })
    });
}

/**
 * put方法,对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(res => {
                resolve(res.data);
                // Loading.service(true).close();
                //  Message({message: ‘请求成功‘, type: ‘success‘});
            })
            .catch(err => {
                reject(err.data)
                // Loading.service(true).close();
                Message({message: ‘加载失败‘, type: ‘error‘});
            })
    });
}

/**
 * delete
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function deletefn(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, params)
            .then(res => {
                resolve(res.data);
                // Loading.service(true).close();
                //  Message({message: ‘请求成功‘, type: ‘success‘});
            })
            .catch(err => {
                reject(err.data)
                // Loading.service(true).close();
                Message({message: ‘加载失败‘, type: ‘error‘});
            })
    });
}

category.js

import {post, get, deletefn, put} from ‘../../utils/axios/axios‘

//获取分类
export const getCategoryList = data => get(‘/item/category/list‘);

//新增一级菜单
export const addCategory = data=> post("/item/category/add",data);
//根据id删除节点
export const deleteCategoryById=data=>deletefn(`/item/category/${data.id}`,data);
//新增子节点
export  const addCategoryByParentId=data=>post(`/item/category/addByParentId`,data);

//根据id编辑节点
export const editCategoryById=data=>put(`/item/category/${data.id}`,data);

category.vue

<template>
    <el-card class="box-card">
        <!--面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-button @click="addCategoryDialog()" style="margin-top: 20px">增加</el-button>
        <!--新增一级对话框-->
        <el-dialog
                title="新增一级"
                :visible.sync="addDialogVisible"
                width="30%"
        >
            <el-form ref="form" :model="addForm" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitCategory">确 定</el-button>
        </el-dialog>
        <!--tree-->
        <el-tree
                :props="defaultProps"
                :data="treeData"
                show-checkbox
                node-key="id"
                :default-expand-all="false"
                :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
            <el-button
                    type="text"
                    size="mini"
                    @click="() => append(data.id,data.isParent)">
            增加
          </el-button>
          <el-button
                  type="text"
                  size="mini"
                  @click="() => remove(data.id)">
            删除
          </el-button>
            <el-button
                    type="text"
                    size="mini"
                    @click="() => edit(data.id,data.isParent,data.parentId,data.name)">
            编辑
          </el-button>
        </span>
      </span>
        </el-tree>

        <!--新增子菜单对话框-->
        <el-dialog
                title="新增子菜单"
                :visible.sync="addCategoryByParentIdDialogVisible"
                width="30%"
        >
            <el-form ref="form" :model="addForm" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="addCategoryByParentIdDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitCategoryByParentId">确 定</el-button>
        </el-dialog>

        <!--编辑节点对话框-->
        <el-dialog
                title="编辑"
                :visible.sync="editCategoryByParentIdDialogVisible"
                width="30%"
        >
            <el-form ref="form" :model="addForm" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="editCategoryByParentIdDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitEditCategoryById">确 定</el-button>
        </el-dialog>
    </el-card>
</template>

<script>
    import {getCategoryList,addCategory,deleteCategoryById,addCategoryByParentId,editCategoryById} from "../../api/item/category";

    export default {
        name: "Category",
        data() {
            return {
                treeData: [],
                defaultProps: {
                    label: ‘name‘
                },
                addDialogVisible: false,
                addForm: {
                    name: ‘‘
                },
                addCategoryByParentIdDialogVisible:false,
                parentId:‘‘,
                isParent:‘‘,
                id:‘‘,
                editCategoryByParentIdDialogVisible:false

            }
        },
        created() {
            this.getlist();

        },
        methods: {
            /**
             * 获取数据
             */
            getlist() {
                getCategoryList().then(res => {
                    console.log("res")
                    console.log(res)
                    console.log("~~~~~~~~~")
                    this.treeData = this.arraytotree(res.data);
                    console.log(this.treeData)
                }).catch(res => {

                })

            },
            handleNodeClick(data) {
                console.log(data);
            },

            //数组转化为树
            arraytotree(arr) {
                var top = [], sub = [], tempObj = {};
                arr.forEach(function (item) {
                    if (item.parentId === 0) { // 顶级分类
                        top.push(item)
                    } else {
                        sub.push(item) // 其他分类
                    }
                    item.children = []; // 默然添加children属性
                    tempObj[item.id] = item // 用当前分类的id做key,存储在tempObj中
                })

                sub.forEach(function (item) {
                    // 取父级
                    var parent = tempObj[item.parentId] || {‘children‘: []}
                    // 把当前分类加入到父级的children中
                    parent.children.push(item)
                })

                return top
            },

            addCategoryDialog() {
                this.addDialogVisible = true;
            },
            /**
             * 新增一级目录
             */
            submitCategory(){
                addCategory(this.addForm).then(res=>{
                    console.log(res)
                    if (res.code===200){
                        this.$message({
                            type: ‘success‘,
                            message: ‘新增一级目录成功‘
                        });
                        this.addForm={}
                        this.addDialogVisible=false
                        this.getlist();
                    }
                    if (res.code===601){
                        this.$message({
                            type: ‘error‘,
                            message: ‘已存在相同的一级目录‘
                        });
                        this.addForm={}
                        this.addDialogVisible=false
                        this.getlist();
                    }
                }).catch(res=>{

                })
            },

            append(id,isParent) {
                this.id=id
                this.isParent=isParent
                console.log(id)
                console.log(isParent)
                this.addCategoryByParentIdDialogVisible=true;
            },

            /**
             * 新增子节点
             */
            submitCategoryByParentId(){
                //把新增子节点的parentId设置为获取到的节点id
                addCategoryByParentId({name:this.addForm.name,isParent:this.isParent,parentId:this.id}).then(res=>{
                    if (res.code===200){
                        this.$message({
                            type:‘success‘,
                            message:‘新增成功‘
                        })
                        this.addCategoryByParentIdDialogVisible=false;
                        this.addForm={}
                        this.getlist();
                    }
                }).catch(res=>{

                })
            },

            /**
             * 通过id删除节点
             * @param id
             */
            remove(id) {
                console.log(id)
                deleteCategoryById({id:id}).then(res=>{
                    if (res.data===200){
                        this.$message({
                            type: ‘success‘,
                            message: ‘删除成功‘
                        });

                    }
                    this.getlist();
                }).catch(res=>{

                })
            },

            edit(id,isParent,parentId,name) {
                this.id=id;
                this.isParent=isParent;
                this.parentId=parentId
                this.addForm.name=name;
                this.editCategoryByParentIdDialogVisible=true;
            },

            /**
             * 根据id编辑节点
             */
            submitEditCategoryById(){
                editCategoryById({id:this.id,name:this.addForm.name,isParent:this.isParent,parentId:this.parentId}).then(res=>{
                    if (res.code===200){
                        this.$message({
                            type: ‘success‘,
                            message: ‘更新成功‘
                        });
                        this.addForm={}
                        this.editCategoryByParentIdDialogVisible=false
                        this.getlist();
                    }
                    if (res.code===801){
                        this.$message({
                            type: ‘error‘,
                            message: ‘更新失败‘
                        });
                        this.addForm={}
                        this.editCategoryByParentIdDialogVisible=false
                        this.getlist();
                    }
                }).catch(res=>{

                })
            }
        }
    }
</script>

<style scoped>
    .el-tree {
        margin-top: 20px;
    }

    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>

后端代码:

实体类:

@Entity
@Table(name = "tb_category")
public class Category {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "parent_id")
    private Integer parentId;
    @Column(name = "is_parent")
    private Integer isParent;
    @Column(name = "sort")
    private Integer sort;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public Integer getIsParent() {
        return isParent;
    }

    public void setIsParent(Integer isParent) {
        this.isParent = isParent;
    }

    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }
}

controller:

@RestController
@RequestMapping(value = "category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有节点
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result findCategory() {
        List<Category> list = categoryService.findCategory();
        if (CollectionUtils.isEmpty(list)) {
            return ResultUtil.error(404, "资源未找到到");
        }

        return ResultUtil.success(list);
    }

    /**
     * 新增一级目录
     * @param category
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addCategory(@RequestBody Category category) {
        Category category1 = categoryService.findCategory(category);
        if (!StringUtils.isEmpty(category1)) {
            return ResultUtil.error(601, "新增失败");
        }
        categoryService.addCategory(category);
        return ResultUtil.success();
    }

    /**
     * 根据id删除节点
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    public Result deleteCategory(@PathVariable("id") Integer id ){
       Optional<Category> optional= categoryService.findCategoryById(id);
       if (!StringUtils.isEmpty(optional)){
           categoryService.deleteCategory(id);
           return ResultUtil.success();
       }

        return  ResultUtil.error(701,"删除失败");
    }

    /**
     * 根据父节点新增子节点
     * @param category
     * @return
     */
    @RequestMapping(value = "/addByParentId",method = RequestMethod.POST)
    public Result saveCategoryById(@RequestBody Category category){
        categoryService.save(category);
        return ResultUtil.success();
    }

    /**
     * 通过id更新节点
     * @param id
     * @param category
     * @return
     */
    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    public Result updateCategory(@PathVariable("id") Integer id,@RequestBody Category category ){
        Optional<Category> optional = categoryService.findCategoryById(id);
        if (!StringUtils.isEmpty(optional)){
           categoryService.updateCategory(category);
           return ResultUtil.success();
        }
        return ResultUtil.error(801,"更新失败");
    }
}

service:

public interface CategoryService {

    List<Category> findCategory();

    void addCategory(Category category);

    Category findCategory(Category category);

    void deleteCategory(Integer id);

    Optional<Category> findCategoryById(Integer id);

    void save( Category category);

    void updateCategory(Category category);
}

serviceImpl:

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public List<Category> findCategory() {
        return categoryDao.findAll();
    }

    @Override
    public void addCategory(Category category) {
        category.setParentId(0);
        category.setIsParent(1);
        category.setName(category.getName());
        category.setSort(1);
        categoryDao.save(category);
    }

    @Override
    public Category findCategory(Category category) {
        categoryDao.findByName(category.getName());
        return  categoryDao.findByName(category.getName());
    }

    @Override
    public void deleteCategory(Integer id) {
        categoryDao.deleteById(id);
    }

    @Override
    public Optional<Category> findCategoryById(Integer id) {
        return categoryDao.findById(id);
    }

    @Override
    public void save( Category category) {
        category.setSort(1);
        categoryDao.save(category);
    }

    @Override
    public void updateCategory(Category category) {
        category.setSort(2);
        categoryDao.save(category);
    }

}

dao:

import com.leyou.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.util.Optional;

public interface CategoryDao extends JpaRepository<Category,Integer> , JpaSpecificationExecutor<Category> {

    Category findByName(String name);

    Optional<Category> findById(Integer id);

}

原文地址:https://www.cnblogs.com/yscec/p/12254062.html

时间: 2024-11-13 16:02:47

elementui Tree 树形控件增删改查的相关文章

elementui Tree 树形控件

数据表结构: 后端代码: @RequestMapping(value = "/list", method = RequestMethod.POST) public Result findCategory(){ List<Category> list = categoryService.findCategory(); if (CollectionUtils.isEmpty(list)){ return ResultUtil.error(404,"资源未找到到&quo

vue_elementUI_ tree树形控件 获取选中的父节点ID

el-tree 的 this.$refs.tree.getCheckedKeys() 只可以获取选中的id 无法获取选中的父节点ID想要获取选中父节点的id;需要如下操作1. 找到工程下的node_modules文件夹 然后查找 element-ui.common.js文件 node_modules\element-ui\lib\element-ui.common.js2. 按Ctrl+F搜索TreeStore.prototype.getCheckedKeys这个方法3. 把// if (chi

vue+element tree(树形控件)组件(2)

今天记录组件的代码和一个调用它的父组件的代码,接口接收数据直接传element直接能用的,也就是经过上一章函数处理过的数据以下是代码 父组件 <template> <commonfiltertree :placeholder="placeholder" :data="data" :showCheckbox="showCheckbox" @check='getcheckdata' :title="title"

winform窗体(六)——DataGridView控件及通过此控件中实现增删改查

DataGridView:显示数据表,通过此控件中可以实现连接数据库,实现数据的增删改查 一.后台数据绑定:    List<xxx> list = new List<xxx>();      dataGridView1.DataSource = list;      //设置不自动生成列,此属性在属性面板中没有      dataGridView1.AutoGenerateColumns = false;      //取消加载默认选中第一行      dataGridView1

【Visual Basic】vb6的ListView控件,对Access2003数据库的增删改查,判断是否有中文、多窗体操作

vb6对Access2003数据库的增删改查并不复杂,可以通过ado对象轻松完成,下面举个小例子,同时说明vb6中的ListView控件的使用.虽然在<[Visual Basic]列表控件ListView的增删改查.模态对话框.禁止窗口调整大小>曾经对VB.NET的ListView控件进行详细的说明,但是证明微软就是个坑爹货,vb6对于ListView实现的代码居然跟VB.NET有着彻底的不同,似乎换了一门语言似得的.改代码什么的最讨厌的. 首先,在vb6生成的工程文件夹中有着一个db1.md

【ExtJs】表格控件Grid的增删改查,利用renderer让操作列actioncolumn使用文字而不是图标

在<[ExtJs]与后台数据库交互的带分页表格组件grid的查询>(点击打开链接)中介绍了Grid控件是怎么分页显示的.再加上对此控件内的数据的增加.删除.修改,就真的是大功告成了.此控件的排序,应该在后台的数据库查询语句中增加一条order by语句即可,前台的排序在分页之后,仅能对当前页进行排序,没有什么意义.下面举一个例子来说明,如果对ExtJs的表格控件Grid进行增删改查 一.基本目标 还是在数据库中有一张user表: 然后在网页中,如下图所示,通过增加.编辑.删除按钮能为这个表格控

【Visual Basic】列表控件ListView的增删改查、模态对话框、禁止窗口调整大小

列表控件ListView是窗体中核心组件之一,在各种窗体程序得到广泛应用.在<[mfc]学生信息管理,实现List控件节点的增删改查>(点击打开链接)中极其难以实现列表控件ListView的增删改查,在vb中可以轻松实现,下面举一个列子来说明这个问题. 如上图的一个ListView控件,点击"添加"按钮,在弹出的模态窗口,可以为ListView控件添加相应的项. 通过"删除"按钮可以删除选中的项.通过"修改"按钮,选中的项的值将会传递

ztree--插件实现增删改查demo(完整版)

ztree--插件实现增删改查demo(完整版) var setting = { async: { enable: true,       //开启异步加载处理 dataFilter: filter  //用于对 Ajax 返回数据进行预处理的函数 }, view: { addHoverDom: addHoverDom, removeHoverDom: removeHoverDom, selectedMulti: false, }, check: { enable: false }, data:

js树形控件—zTree使用总结(转载)

0 zTree简介 树形控件的使用是应用开发过程中必不可少的.zTree 是一个依靠 jQuery 实现的多功能 “树插件”.优异的性能.灵活的配置.多种功能的组合是 zTree 最大优点. 0.0 zTree的特点 最新版的zTree将核心代码按照功能进行了分割,不需要的代码可以不用加载,如普通使用只需要加载核心的jquery.ztree.core-3.5.js,需要使用勾选功能加载jquery.ztree.excheck-3.5.min.js,需要使用编辑功能加载jquery.ztree.e