SPA项目动态树、数据表格、分页、CRUD、表单验证

本文详细介绍了如何在Vue.js单页应用(SPA)中实现动态左侧菜单,利用Element UI创建数据表格、分页功能,并进行了增删改查操作及表单验证。首先,通过后端接口获取数据动态绑定菜单,接着实现路由跳转,接着创建数据表格展示数据,最后添加表单验证以确保数据质量。整个过程涵盖了Vue组件、路由配置、HTTP请求、数据绑定和表单交互等多个方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

       上一篇文章分享了SPA项目实现首页的导航条以及左侧菜单。本篇文章将要完善SPA项目的功能。将左侧菜单动态绑值,完成页面的数据表格、分页。对其进行增删改查以及增加、修改的表单验证。


一、动态树

        原来我们的左侧树菜单是定死的数据,但是我们现在要将它盘活。将它绑为数据库的数据。

        确定模板,我们只有二级菜单,所以改一下之前的界面,得到数据通过v-for将数据绑定到左侧菜单就OK。

        调用后台接口获得,左侧树节点的内容。将数据绑定到界面。

        新建需要跳转页面的菜单项的路由,这里我们用文章管理做示例。因为跳转的地方是在AppMain里面,所以这个路由是AppMain的子路由。

        做好路由的关系映射后,就可以测试看效果。

实现步骤: 

1、确定导航菜单的结构

2、el-menu组件实现路由跳转当前项

3、获得数据

4、绑定数据

5、新建菜单项的路由

6、做好路由映射关系

7、测试

具体的实现步骤就不展示了。直接放代码,可以自己根据实现步骤来完成。 

注意事项:

注1:要实现路由跳转,先要在el-menu标签上添加router属性,然后只要在每个el-menu-item标签内的index属性设置一下url即可实现点击el-menu-item实现路由跳转。
 

注2:导航当前项,在el-menu标签中绑定  :default-active="$route.path",注意是绑定属性,
           不要忘了加“:”,当$route.path等于el-menu-item标签中的index属性值时则该item为当前项。

        LeftNav.vue 

<template>
  <el-menu router :default-active="$route.path" default-active="2" class="el-menu-vertical-demo" background-color="#334157" text-color="#fff"
    active-text-color="#ffd04b" :collapse="collapsed">
    <!-- <el-menu default-active="2" :collapse="collapsed" collapse-transition router :default-active="$route.path" unique-opened class="el-menu-vertical-demo" background-color="#334157" text-color="#fff" active-text-color="#ffd04b"> -->
    <div class="logobox">
      <img class="logoimg" src="../assets/img/logo.png" alt="">
    </div>
    <el-submenu :index="'id_'+m.treeNodeId" v-for="m in menus">
      <template slot="title">
        <i :class="m.icon"></i>
        <span>{{m.treeNodeName}}</span>
      </template>
      <el-menu-item :key="'id_'+m2.treeNodeId" :index="m2.url" v-for="m2 in m.children">
        <i :class="m2.icon"></i>
        <span>{{m2.treeNodeName}}</span>
      </el-menu-item>
    </el-submenu>
  </el-menu>
</template>
<script>
  export default {
    data() {
      return {
        collapsed: false,
        // 存放所有一级菜单
        menus:[]
      }
    },
    created() {

      let url = this.axios.urls.SYSTEM_MENU_TREE;
      this.axios.post(url, {}).then(resp => { //代表成功
        console.log(resp);
        this.menus = resp.data.result;
      }).catch(function() { //代表失败

      });
      this.$root.Bus.$on('collapsed-aside', (v) => {
        this.collapsed = v;
      })
    }
  }
</script>
<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 240px;
    min-height: 400px;
  }

  .el-menu-vertical-demo:not(.el-menu--collapse) {
    border: none;
    text-align: left;
  }

  .el-menu-item-group__title {
    padding: 0px;
  }

  .el-menu-bg {
    background-color: #1f2d3d !important;
  }

  .el-menu {
    border: none;
  }

  .logobox {
    height: 40px;
    line-height: 40px;
    color: #9d9d9d;
    font-size: 20px;
    text-align: center;
    padding: 20px 0px;
  }

  .logoimg {
    height: 40px;
  }
</style>

        router/index.js

 路由关系映射

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/views/Login'
import Reg from '@/views/Reg'
import AppMain from '@/components/AppMain'
import LeftNav from '@/components/LeftNav'
import TopNav from '@/components/TopNav'
import Articles from '@/views/sys/Articles'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/Login',
      name: 'Login',
      component: Login
    },
    {
      path: '/Reg',
      name: 'Reg',
      component: Reg
    },
    {
        path: '/AppMain',
        name: 'AppMain',
        component: AppMain,
        children: [{
            path: '/LeftNav',
            name: 'LeftNav',
            component: LeftNav
          },
          {
            path: '/TopNav',
            name: 'TopNav',
            component: TopNav
          },
          {
            path: '/sys/Articles',
            name: 'Articles',
            component: Articles
          }
      ]
    }
  ]
})

        效果预览:

左侧菜单动态树:

 

 

 菜单项路由跳转:

 图中效果需将下面的内容完成后才会展示。

二、数据表格及分页

既然完成了左侧的动态树以及路由的跳转,下一步就要将数据展示到我们跳转到的界面啦。

数据表格我们可以参考elementUI官网 

我们找到需要的代码段进行修改,改成我们需要的样子。 (根据自身需求来)

在数据表格的上方添加 表单的查询。

在数据表格的下方添加 分页

        Articles.vue 

<template>
	<div>
		<el-form :inline="true" :model="formInline" class="user-search">
			<el-form-item label="搜索:">
				<el-input size="small" v-model="formInline.title" placeholder="输入文章标题"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
				<!-- <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button> -->
			</el-form-item>
		</el-form>
		<!--列表-->
		<el-table size="small" :data="listData" element-loading-text="拼命加载中" style="width: 100%;">
			<el-table-column align="center" type="selection" min-width="1">
			</el-table-column>
			<el-table-column sortable prop="id" label="文章ID" min-width="1">
			</el-table-column>
			<el-table-column sortable prop="title" label="文章标题" min-width="3">
			</el-table-column>
			<el-table-column sortable prop="body" label="文章内容" min-width="5">
			</el-table-column>
			<!-- <el-table-column align="center" label="操作" min-width="300">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column> -->
		</el-table>
		<el-pagination style="margin-top: 20px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
		 :current-page="formInline.page" :page-sizes="[10, 20, 30, 50]" :page-size="100" layout="total, sizes, prev, pager, next, jumper"
		 :total="total">
		</el-pagination>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				listData: [],
				formInline: {
					page: 1,
					rows: 10,
					title: ''
				},
				total: 0
			};
		},
		methods: {

			handleSizeChange(rows) {
				this.formInline.page = 1;
				this.formInline.rows = rows;
				this.search();
			},
			handleCurrentChange(page) {
				this.formInline.page = page;
				this.search();
			},
			doSearch(params) {
				let url = this.axios.urls.SYSTEM_ARTICLE_LIST;
				

				this.axios.post(url, params).then((response) => {
					console.log(response);
					this.listData = response.data.result;
					this.total = response.data.pageBean.total;
				}).catch(function(error) {
					console.log(error);
				});
			},
			search(){
				this.doSearch(this.formInline);
			}
		},
		created() {
			this.doSearch({});
		}
	}
</script>

<style>

</style>

 效果预览:

 三、表单验证

完成上述部分内容后,想要完善当前页面需要实现添加,编辑、删除。

而增加和编辑我们要对它进行一个表单验证,不能什么都放进去。

 Form组件提供了表单验证的功能,只需要通过 rules 属性传入约定的验证规则,
   并将Form-Item的prop属性设置为需校验的字段名即可

 

 同样我们来看elementUI官网。

 

 对红框中的内容进行修改,改成符合我们需求的样子。

因为id为自增,我们只需要用到文章标题和文章内容两个字段。

我们看一下代码展示:

这里是符合我的需求的表单验证的代码

rules: {
          title: [{
              required: true,
              message: '请输入文章标题',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 15,
              message: '长度在 3 到 15 个字符',
              trigger: 'blur'
            }
          ],
          body: [{
            required: true,
            message: '请输入文章内容',
            trigger: 'blur'
          }]
        }

注意: 

有多个表单,怎么在提交进行区分?
        我们在rules这里写了对表单的验证规则,但是我们如何在methods里进行指定的表单进行认证,
        所以我们一开始就在el-form里写了 ref="ruleForm",我们在methods里就可以用


   注2:清空表单验证信息
        this.$refs[formName].resetFields();

 

 看一下效果:

如果我们什么都不填直接保存

如果我们填的内容不符合验证的规则:

 

四、CRUD

完成上述内容后,这一个简单的页面还剩下完成增加、修改和删除

在我的代码中增加和修改共用一个事件,如何区分它们?

我通过id来区分,如果是新增那么它的id会是0,如果代码不为0则是修改。 

新增/修改: 

        点击添加判断是新增还是修改(如果是修改还需要拿到当前行)弹出一个dialog,新增则文本框为空。修改则进行数据的回显。

        输入/修改为符合条件的内容。

        点击保存 

        将数据作为参数,调用对应的后端接口进行交互。

        成功或者失败进行提示。

        调用查询方法。

 注意:

我们的新增和修改共用一个事件和对象,如果刚使用过修改,新增的窗口会有刚刚的修改的内容残留。

所以我们要定义一个方法,用于清空表单的对象的数据。

 删除:

        点击删除

        提示是否确认删除,取消则关闭窗口并提示取消

        成功则拿到当前行

        调用对应的后台接口进行交互,删除数据。

        提示删除成功

        调用查询方法。

文章管理界面完整代码展示:

 

<template>
  <div>
    <!-- 搜索 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索:">
        <el-input size="small" v-model="formInline.title" placeholder="文章标题"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table size="small" :data="listData" highlight-current-row border element-loading-text="拼命加载中"
      style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="id" label="文章ID" width="300">
      </el-table-column>
      <el-table-column sortable prop="title" label="文章标题" width="300">
      </el-table-column>
      <el-table-column sortable prop="body" label="文章内容" width="300">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="1">
        <template slot-scope="scope">
          <el-button size="mini" @click="doEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 20px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="formInline.page" :page-sizes="[10, 20, 30, 50]" :page-size="100"
      layout="total, sizes, prev, pager, next, jumper" :total="formInline.total">
    </el-pagination>

    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @before-close="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="文章标题" prop="title">
          <el-input size="small" v-model="editForm.title" auto-complete="off" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="body">
          <el-input size="small" v-model="editForm.body" auto-complete="off" placeholder="请输入文章内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Articles',
    data() {
      return {
        listData: [],
        formInline: {
          page: 1,
          rows: 10,
          title: ''
        },
        total: 0,
        title: '',
        editFormVisible: false,
        editForm: {
          title: '',
          body: '',
          id: 0
        },
        rules: {
          title: [{
              required: true,
              message: '请输入文章标题',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 15,
              message: '长度在 3 到 15 个字符',
              trigger: 'blur'
            }
          ],
          body: [{
            required: true,
            message: '请输入文章内容',
            trigger: 'blur'
          }]
        }
      };
    },
    methods: {
      handleSizeChange(rows) {
        console.log("当前查询页数据量:" + rows)
        this.formInline.page = 1;
        this.formInline.rows = rows;
        this.search();
      },
      handleCurrentChange(page) {
        console.log("当前页为:" + page)
        this.formInline.page = page;
        this.search();
      },
      doSearch(param) {
        let url = this.axios.urls.SYSTEM_ARTICLE_LIST;
        this.axios.post(url, param).then(resp => { //代表成功
          console.log(resp);
          this.listData = resp.data.result;
          this.formInline.total = resp.data.pageBean.total;
        }).catch(function() { //代表失败

        });
        this.$root.Bus.$on('collapsed-aside', (v) => {
          this.collapsed = v;
        })
      },
      search() {
        this.doSearch(this.formInline)
      },
      closeDialog() {
        this.clearData();
      },
      handleEdit() {
        this.clearData();
        this.editFormVisible = true;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url;
            if (this.editForm.id == 0) {
              url = this.axios.urls.SYSTEM_ARTICLE_ADD;
            } else {
              url = this.axios.urls.SYSTEM_ARTICLE_EDIT;
            }
            // let url = 'http://localhost:8080/T216_SSH/vue/userAction_login.action';

            this.axios.post(url, this.editForm).then((resp) => {
              console.log(resp);
              this.clearData();
              this.search();
            }).catch(function(error) {
              console.log(error);
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      doEdit(index, row) {
        this.editForm.id = row.id;
        this.editForm.title = row.title;
        this.editForm.body = row.body
        this.editFormVisible = true;
        this.title = '编辑窗体';
      },
      clearData() {
        this.title = '';
        this.editForm.id = 0;
        this.editForm.title = '';
        this.editForm.body = '';
        this.editFormVisible = false;
      },
      deleteUser(index, row) {
        let url = this.axios.urls.SYSTEM_ARTICLE_DEL;
        this.axios.post(url, {
          id: row.id
        }).then((response) => {
          console.log(response);
          this.clearData();
          this.search();
        }).catch(function(error) {
          console.log(error);
        });
      }
    },
    created() {
      this.doSearch({})
    }
  }
</script>

<style>
</style>

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值