vue2新增删除

(只是页面实现,不涉及数据库)

list组件:

cpp 复制代码
 <button @click="onAdd">新增</button>
         <el-table
            :header-cell-style="{ textAlign: 'center' }"  
            :cell-style="{ textAlign: 'center' }"
          :data="tableData"
          style="width: 100%">
           <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="id"
            label="序号"
            max-width="100">
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            max-width="100">
          </el-table-column>
          <el-table-column
            prop="address"
            max-width="100"
            label="地址">
          </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit( scope.row)">编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
        </el-table>
          // 引入  新增弹框组件
        <Add  :visible.sync="dialogVisible" :title="title" />
          <!-- 引入 编辑弹框组件 -->
        <Edit  :visible.sync="dialog"  :title="titleedit" :item="ruleForm"  @save="saveItem" />
js部分:
     created(){
     //获取列表数据
           this.getUser(),
           
          // 监听 'formSubmitted' 事件,当表单数据提交时更新列表
          EventBus.$on('formSubmitted', (newData) => {
               // 计算当前 tableData 中的最大 id   添加数据时候 id按照顺序自增
            const maxId = this.tableData.length > 0 ? Math.max(...this.tableData.map(item => item.id)) : 0;
            
            // 设置新的 id
            newData.id = maxId + 1;
            this.tableData.push(newData); // 添加新数据到 dataList
          });
      },
      methods:{
          // 点击新增按钮
		    onAdd(){
		          this.dialogVisible=true;
		        },

		//  删除
		handleDelete( row ) {
		  console.log(row)
		  this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
		            confirmButtonText: '确定',
		            cancelButtonText: '取消',
		            type: 'warning',
		            center: true
		          }).then(() => {
		            // 通过 row 数据找到索引并删除
		      const itemIndex = this.tableData.findIndex(item => item.id === row.id);
		      console.log(itemIndex)
		      if (itemIndex !== -1) {
		        this.tableData.splice(itemIndex, 1);
		      }
		      this.reassignIds()
		            this.$message({
		              type: 'success',
		              message: '删除成功!'
		            });
		          }).catch(() => {
		            this.$message({
		              type: 'info',
		              message: '已取消删除'
		            });
		          });
		    
		},

			// 重新分配数据的id  保证其自增
			reassignIds(){
			  this.tableData.forEach((item,index)=>{
			    item.id=index+1
			  })
			}
}

// 编辑
handleEdit(row){
  console.log(row,'row')
     this.dialog=true;
     this.titleedit="编辑"
     this.ruleForm={...row}  // // 复制项的数据到 列表中
},
 // 保存编辑后的项
    saveItem(updatedItem) {
      console.log(updatedItem,'updatedItem')
      // 更新列表中的数据,通常会同步到后端
      const index = this.tableData.findIndex(item => item.id === updatedItem.id);
      if (index !== -1) {
         this.$set(this.tableData, index, { ...updatedItem }); // 使用 Vue.set 来确保响应式更新数据列表
        console.log(this.tableData,'this.tableData[index]')
      }

    }

Add组件:

cpp 复制代码
        <el-dialog
            :title="title"
            :visible.sync="visible"
            width="30%"
            center
          >
                <el-form :model="ruleForm"  :rules="rules"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="序号" prop="id">
                        <el-input type="text" v-model="ruleForm.id" ></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input type="text" v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input v-model.number="ruleForm.address"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
 
 js部分:
 import {EventBus} from '../util/eventBus';
   export default {
    data() {
      return {
        ruleForm:{
            // id:'',
            name:'',
            address:''
        },
      rules: {
        // id: [
        //   { required: true, message: '序号不能为空', trigger: 'blur' }
        // ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ]
      }
      }
    },
    props:{
        visible:{
            typeof:Boolean,
            default:false
        },
        title:{
            typeof:String,
            default:''
        }
    },
    watch:{
        visible(newVal){
            this.$emit('update:visible', newVal);
        }
    },
    methods:{
        closeDialog(){
             this.$emit('update:visible', false); 
        },
// 提交
// 提交表单
      submitForm(formName) {
      this.$refs[formName].validate((valid) => {
      if (valid) {
          // 提交数据到 Vuex
           const formCopy = { ...this.ruleForm }; // 创建 ruleForm 的副本
          EventBus.$emit('formSubmitted', formCopy);
          this.$message.success('提交成功');
          
          this.ruleForm.name=''
          this.ruleForm.address=''
          this.closeDialog();
       
        } else {
          // this.$message.error('表单验证失败');
        }
      });
    },
        // 重置
     resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  };
</script>
            
cpp 复制代码
event-bus.js中:

// event-bus.js
import Vue from 'vue';
// 创建一个空的 Vue 实例作为事件总线
export const EventBus = new Vue();
cpp 复制代码
// 编辑弹框
<template>
  <div>
        <el-dialog
            :title="title"
            :visible.sync="visible"
            width="30%"
            center
          >
                <el-form :model="ruleForm"  :rules="rules"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="姓名" prop="name">
                        <el-input type="text" v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input v-model.number="ruleForm.address"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
  </div>
</template>

<script>
import {EventBus} from '../util/eventBus'

  export default {
    data() {
      return {
        ruleForm:{
            name:'',
            address:''
        },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ]
      }
      }
    },
    props:{
        visible:{
            typeof:Boolean,
            default:false
        },
        title:{
            typeof:String,
            default:''
        },
        item:{
            typeof:Object,
            default:()=>({})
        }
    },
    watch:{
        visible(newVal){
            this.$emit('update:visible', newVal);
        },
        item(newItem){
            this.ruleForm={...newItem}
        }
    },
    methods:{

        closeDialog(){
               this.$emit('update:visible', false); 
        },

        // 重置
      resetForm(formName) {
        console.log(formName,'formName')
        this.$refs[formName].resetFields();
        this.ruleForm.name='',
        this.ruleForm.address=''
      },
 //  提交
      submitForm(){
        this.$emit('save',this.ruleForm)
        this.closeDialog()
      }
    }
  };
</script>
相关推荐
狗头大军之江苏分军7 小时前
iPhone 17 vs iPhone 17 Pro:到底差在哪?买前别被忽悠了
前端
小林coding7 小时前
再也不怕面试了!程序员 AI 面试练习神器终于上线了
前端·后端·面试
文心快码BaiduComate8 小时前
WAVE SUMMIT深度学习开发者大会2025举行 文心大模型X1.1发布
前端·后端·程序员
babytiger8 小时前
python 通过selenium调用chrome浏览器
前端·chrome
passer9818 小时前
基于webpack的场景解决
前端·webpack
华科云商xiao徐8 小时前
Java并发编程常见“坑”与填坑指南
javascript·数据库·爬虫
奶昔不会射手8 小时前
css3之grid布局
前端·css·css3
举个栗子dhy8 小时前
解决在父元素上同时使用 onMouseEnter和 onMouseLeave时导致下拉菜单无法正常展开或者提前收起问题
前端·javascript·react.js