vue.js3+element-plus+typescript add,edit,del,search

vite.config.ts

TypeScript 复制代码
server: {
  cors: true, // 默认启用并允许任何源
  host: '0.0.0.0', // 这个用于启动
  port: 5110, // 指定启动端口
  open: true, //启动后是否自动打开浏览器  
  proxy: {
      '/api': {
        target: 'http://localhost:8081/',  //实际请求地址,数据库的rest APIs
        changeOrigin: true      
      },
 }

数据来源于前面文章的介绍的方式

TypeScript 复制代码
import axios from "axios";

/* eslint-disable class UserinfoDataService*/
/**
 * Userinfo Rest API
 * 和前文章的各数据操作,可以用其一任一种
 */
class UserinfoDataService
{


  /**
   * 查看所有记录    getAll():Promise<any> {
   * @returns 
   */ 
  getAllData(){
    
    axios.get('/api/userinfos')
    .then(response=>{
        console.log(response.data);
        return response.data;
    })
    .catch(error=>{
        console.log(error);
        return null
    });
    //console.log(axios.get("/tutorials"));
   // return axios.get("/api/tutorials");// http.get("/tutorials");//



  }

/**
 * 2 查询所有记录
 */
getAll(): Promise<any>{

  return axios.get("/api/userinfos");// http.get("/tutorials");//
}

/**
 * 登录
 * @param userName 
 * @param userPassword 
 * @returns 
 */
userlogin(userName:any,userPassword:any):Promise<any> 
{
  return axios.get(`/api/userinfos/?userName=${userName}&userPassword=${userPassword}`);
}

  /**
   * 查询一条记录
   * @param id 
   * @returns 
   */
  get(id: any): Promise<any> {
    console.log(id);
    
    return axios.get(`/api/userinfos/${id}`);//http.get(`/api/tutorials/${id}`);
  }
  /**
   * 添加
   * @param data 
   * @returns 
   */
  create(data: any): Promise<any> {



    return axios.post("/api/userinfos", data);
  }
  /**
   * 更新
   * @param id 
   * @param data 
   * @returns 
   */
  update(id: any, data: any): Promise<any> {
    return axios.put(`/api/userinfos/${id}`, data);
  }


  /**
   * 删除
   * @param id 
   * @returns 
   */
  delete(id: any): Promise<any> {
    return axios.delete(`/api/userinfos/${id}`);
  }

  /**
   *删除所有
   * @returns 
   */
  deleteAll(): Promise<any> {
    return axios.delete(`/api/api/userinfos`);
  }
  /**
   * 查找
   * @param username 
   * @returns 
   */
  findByTitle(username: string): Promise<any> {
    return axios.get(`/api/userinfos?username=${username}`);
  }
}
// new TutorialDataService()
export default new UserinfoDataService();

调用:

TypeScript 复制代码
<!--
*
 * _______________#########_______________________ 
 * ______________############_____________________ 
 * ______________#############____________________ 
 * _____________##__###########___________________ 
 * ____________###__######_#####__________________ 
 * ____________###_#######___####_________________ 
 * ___________###__##########_####________________ 
 * __________####__###########_####_______________ 
 * ________#####___###########__#####_____________ 
 * _______######___###_########___#####___________ 
 * _______#####___###___########___######_________ 
 * ______######___###__###########___######_______ 
 * _____######___####_##############__######______ 
 * ____#######__#####################_#######_____ 
 * ____#######__##############################____ 
 * ___#######__######_#################_#######___ 
 * ___#######__######_######_#########___######___ 
 * ___#######____##__######___######_____######___ 
 * ___#######________######____#####_____#####____ 
 * ____######________#####_____#####_____####_____ 
 * _____#####________####______#####_____###______ 
 * ______#####______;###________###______#________ 
 * ________##_______####________####______________ 
 * 
 * @Author: geovindu
 * @Date: 2024-08-26 19:55:02
 * @LastEditors: geovindu
 * @LastEditTime: 2024-08-27 20:24:32
 * @FilePath: \vue\vuetest\src\components\tablebind.vue
 * @Description: geovindu
 * @lib,packpage: 
 * 
 * @IDE: vscode
 * @jslib: node 20 vue.js 3.0
 * @OS: windows10
 * @database: mysql 8.0  sql server 2019 postgreSQL 16
 * Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved. 
 -->
 
 <template>
    <div style="padding: 10px"> 
        <ElConfigProvider :locale="zhCn">
        <ElInput style="width: 300px" placeholder="请输入名称..." v-model="name" clearable></ElInput>
        <ElButton type="primary" @click="search" style="margin-left: 5px">查询数据</ElButton>
 
        <ElButton type="primary" @click="handleAdd">新增数据</ElButton>
 
        <div style="margin: 10px 0">
            <ElTable :data="paginatedData" border style="width: 100%">  
                <ElTableColumn prop="id" label="ID" width="20"/>     
                <ElTableColumn prop="userName" label="用户名" width="80"/>        
                <ElTableColumn prop="userReal" label="姓名" width="80"/>
                <ElTableColumn prop="userPassword" label="密码"/>
                <ElTableColumn prop="userIsOk" label="否可用"/>
                <ElTableColumn prop="userMail" label="邮件"/>
                <ElTableColumn prop="userMobile" label="手机号码"/>
                <ElTableColumn prop="createdAt" label="日期" width="80"/>
                <ElTableColumn label="操作">
                    <template #default="scope">
                        <ElButton type="text" size="small" @click="handleEdit(scope.row, scope.$index)">编辑</ElButton>  
                        <ElButton type="danger" size="small" @click.prevent="remove(scope.$index)">删除</ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
            <div class="pagination-block">  
        <ElPagination  
          background  
          layout="prev, pager, next, jumper, total, sizes"  
          :current-page="state.page"  
          :page-size="state.limit"  
          :page-sizes="[10, 20, 30, 40]"  
          :total="total"  
          @current-change="handleCurrentChange"  
          @size-change="handleSizeChange"  
        />  
      </div>  
        </div>
 
        <!--弹窗-->
        <ElDialog v-model="dialogFormVisible" title="信息" width="40%">
            <ElForm :model="form" label-width="100px" style="padding-right:30px ">
                <ElFormItem label="ID">
                    <ElInput v-model="form.id" autocomplete="off"/>
                </ElFormItem>                
                <ElFormItem label="用户名">
                    <ElInput v-model="form.userName" autocomplete="off"/>
                </ElFormItem>
                <ElFormItem label="姓名">
                    <ElInput v-model="form.userReal" autocomplete="off"/>
                </ElFormItem>
                <ElFormItem label="密码">
                    <ElInput v-model="form.userPassword" autocomplete="off"/>
                </ElFormItem>
                <ElFormItem label="邮件">
                    <ElInput v-model="form.userMail" autocomplete="off"/>
                </ElFormItem>
                <ElFormItem label="手机号码">
                    <ElInput v-model="form.userMobile" autocomplete="off"/>
                </ElFormItem>
                <ElFormItem label="是否可用">
                    <ElCheckbox v-model="form.userIsOk"/>
                </ElFormItem>
                <ElFormItem label="日期">                    
                    <ElDatePicker
        v-model="form.createdAt"
        type="date"
        placeholder="Pick a day"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"        
        :disabled-date="disabledDate"
        :shortcuts="shortcuts"
        :size="size"
      />     
      </ElFormItem>

            </ElForm>
            <template #footer>
      <span class="dialog-footer">
        <ElButton @click="dialogFormVisible = false">取消</ElButton>
        <ElButton type="primary" @click="save">确认</ElButton>
      </span>
            </template>
        </ElDialog>
    </ElConfigProvider>
    </div>
</template>
<script lang="ts" setup>
  import { ElMessageBox,ElTable,ElButton,ElTableColumn,ElDialog,ElForm,ElFormItem,ElInput,ElDatePicker,ElConfigProvider,ElCheckbox } from "element-plus";
 //https://element-plus.org/zh-CN/guide/i18n.html
  import zhCn from 'element-plus/es/locale/lang/zh-cn'//中文
  import {reactive, ref,computed} from "vue";
  import  UserinfoDataService from "../services/UserinfoDataService";
  import router from "@/router"; //路由配置文件
  import Crypoto from "../common/Cryptographer"; //;加密

    const total=ref(0);
  
     //
  const state = reactive({  
    page: 1,  
    limit: 10,  
  });  


  // 计算属性用于分页  
  const paginatedData = computed(() => {  
  const start = (state.page - 1) * state.limit;  
  const end = start + state.limit;  
  total.value=tableData.value.length;
    return tableData.value.slice(start, end);  
  });  
    
  // 改变页码  
  const handleCurrentChange = (e: number) => {  
    state.page = e;  
  };      
  // 改变页数限制  
  const handleSizeChange = (e: number) => {  
    state.limit = e;  
  };  

    //https://element-plus.org/zh-CN/component/date-picker
    const size = ref<'default' | 'large' | 'small'>('default');
    const shortcuts = [
  {
    text: 'Today',
    value: new Date(),
  },
  {
    text: 'Yesterday',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: 'A week ago',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

    //
    const tableData = ref([{}]);
    //读数据
    UserinfoDataService.getAll().then(response=>{     
                  console.log("class处理成功情况2");
                  console.log(response.data);
                  tableData.value=response.data;

              })
              .catch(error=>{
                  console.log(error);
              });
     
    const dialogFormVisible = ref(false)
    const form = reactive({
        id:total,
        userName:"",
        userReal:"",
        userPassword:"",
        userIsOk:false,
        userMail:"",
        userMobile:"",
        createdAt:""

    })
    //全局保存编辑的行号
    const globalIndex = ref(-1)
    const name = ref('')
 
    //新增数据 设置新的空的绑值对象 打开弹窗
    const handleAdd = () => {
        //生成最大的ID
        form.id=tableData.value.length+1;
        form.userName = '';  
        form.userReal="";
        form.userPassword = '';  
        form.userIsOk = false;
        form.userMail="";
        form.userMobile="";
        form.createdAt="";
        dialogFormVisible.value = true;
    }
 
    //保存数据,把数据插入到tableData中,并刷新页面,弹窗关闭
    const save = () => {
        if (globalIndex.value >= 0) {
            //表示编辑
            tableData.value[globalIndex.value,20] = form    
            //还原回去
            globalIndex.value = -1

            UserinfoDataService.update(form.id,form); //修改成功 (密码需要加密一下)
            
            router.push('tablebind')

        } else {

            //新增
            tableData.value.push(form)
            UserinfoDataService.create(form); //添加成功!(密码需要加密一下)
            router.push('tablebind')
        }
 
        dialogFormVisible.value = false
    }
 
    //编辑数据 先赋值到表单再弹窗
    const handleEdit = (row: {id:number, userName: string; userReal:string,userPassword: string; userIsOk:boolean,userMail:string,userMobile:string,createdAt:string}, index: number) => {
        const newObj = Object.assign({}, row)
        form.id=newObj.id;
        form.userName =newObj.userName;
        form.userReal=newObj.userReal;
        form.userPassword=newObj.userPassword;
        form.userIsOk=newObj.userIsOk;
        form.userMail=newObj.userMail; //.toLocaleDateString()
        form.userMobile=newObj.userMobile;
        form.createdAt=newObj.createdAt;
        console.log(form);
        // reactive(newObj)
        //把当前编辑的行号赋值给全局保存的行号
        globalIndex.value = index;
        console.log(globalIndex.value);
        dialogFormVisible.value = true;
        
    }
 
    //删除数据 从index位置开始,删除一行即可 删除前有一个提示为好
    const remove = (index:any) => {
        tableData.value.splice(index, 1)

       // UserinfoDataService.delete(form.id) //删除

    }
    
    //查询数据有问题,需要修改
    const search = () =>{

        tableData.value = tableData.value.filter(v =>v.userName.includes(form.userName)) //userName.value

       // UserinfoDataService.getAll(form.userName)
    }
</script>

还有BUG,待完善

输出:

相关推荐
王解13 分钟前
Vue CLI 脚手架创建项目流程详解 (2)
前端·javascript·vue.js
刘大浪17 分钟前
vue.js滑动到顶便锁定位置
前端·javascript·vue.js
小金刚®23 分钟前
构建简洁之美:我的第一个前端页面
前端
ordinary901 小时前
指令-v-for的key
前端·javascript·vue.js
rpa_top1 小时前
RPA 助力电商:自动化商品信息上传,节省人力资源 —— 以影刀 RPA 为例【rpa.top】
大数据·前端·人工智能·自动化·rpa
新时代农民工--小明1 小时前
前端自动化部署更新,自动化打包部署
运维·前端·自动化
前端Hardy1 小时前
HTML&CSS:酷炫的3D开关控件
前端·javascript·css·3d·html
小马超会养兔子1 小时前
如何写一个数字老虎机滚轮
开发语言·前端·javascript·vue
武昌库里写JAVA2 小时前
使用React Strict DOM改善React生态系统
数据结构·vue.js·spring boot·算法·课程设计
m0_672449602 小时前
前端(组件传参案例)
前端