当前位置: 首页 > article >正文

vue2新增删除

(只是页面实现,不涉及数据库)
list组件:

 <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组件:

        <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>
            
event-bus.js中:

// event-bus.js
import Vue from 'vue';
// 创建一个空的 Vue 实例作为事件总线
export const EventBus = new Vue();

// 编辑弹框
<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>




http://www.kler.cn/a/471797.html

相关文章:

  • Idea(中文版) 项目结构/基本设置/设计背景
  • Linux(Centos 7.6)命令详解:mkdir
  • Wireshark基本使用
  • LabVIEW四边形阻抗继电器
  • 需求分析基本操作流程
  • React使用Redux
  • Hive sql执行文件合并配置参数
  • vue3+vite+tdesign实现日历式可编辑的排课班表
  • 概率论与数理统计--期末
  • 第21章 汇编语言--- DMA(直接内存访问)
  • A second-price auction
  • MySQL 间隙锁避免“可重复读”出现“幻读”
  • OpenCV在现代社会中的应用
  • 【机器学习:四、多输入变量的回归问题】
  • MySQL 如何赶上 PostgreSQL 的势头?
  • 特种设备安全管理人员免费题库限时练习(判断题)
  • NVIDIA在CES 2025上的三大亮点:AI芯片、机器人与自动驾驶、全新游戏显卡
  • [创业之路-241]:《从偶然到必然-华为研发投资与管理实践》-2- IPD流程中的业务线、技术线、职能支撑线
  • 【STM32】I2C为什么要开漏输出和上拉电阻
  • [微服务]redis主从集群搭建与优化