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

 

vite.config.ts

1
2
3
4
5
6
7
8
9
10
11
server: {
  cors: true, // 默认启用并允许任何源
  host: '0.0.0.0', // 这个用于启动
  port: 5110, // 指定启动端口
  open: true, //启动后是否自动打开浏览器 
  proxy: {
      '/api': {
        target: 'http://localhost:8081/',  //实际请求地址,数据库的rest APIs
        changeOrigin: true     
      },
 }

  

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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();

  

调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<!--
*
 * _______________#########_______________________
 * ______________############_____________________
 * ______________#############____________________
 * _____________##__###########___________________
 * ____________###__######_#####__________________
 * ____________###_#######___####_________________
 * ___________###__##########_####________________
 * __________####__###########_####_______________
 * ________#####___###########__#####_____________
 * _______######___###_########___#####___________
 * _______#####___###___########___######_________
 * ______######___###__###########___######_______
 * _____######___####_##############__######______
 * ____#######__#####################_#######_____
 * ____#######__##############################____
 * ___#######__######_#################_#######___
 * ___#######__######_######_#########___######___
 * ___#######____##__######___######_____######___
 * ___#######________######____#####_____#####____
 * ____######________#####_____#####_____####_____
 * _____#####________####______#####_____###______
 * ______#####______;###________###______#________
 * ________##_______####________####______________
 *
 * @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,待完善

输出:

 

 

search:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//查询数据
const search = () =>{
 
     
 
   if (searchName.value !== '') {
      //tableData.value为表格数据的值
     console.log(searchName.value);
     console.log('temp:');
     console.log(temtable.value)
     const temp = ref([])
     const lst=ref([]);
     temp.value=tableData.value.filter(
      //(v: any) =>v.searchName.includes(searchName.value)
      (item: any) => item.userName.indexOf(searchName.value) >= 0  //查询某字段中的数据 || item.userReal.indexOf(searchName.value) >= 0
      //(item: any) =>item.userName.includes(searchName.value)
    );
    lst.value.push(temp.value);
    temp.value=tableData.value.filter(
      //(v: any) =>v.searchName.includes(searchName.value)
      (item: any) => item.userReal.indexOf(searchName.value) >= 0 //查询某字段中的数据
      //(item: any) =>item.userName.includes(searchName.value)
    );
    lst.value.push(temp.value);
 
    console.log('search:');
     console.log(lst.value)
     tableData.value = tableData.value.filter(
      //(v: any) => v.userName.indexOf(searchName.value) >= 0 
      (v: any) =>v.userName.includes(searchName.value) || v.userReal.includes(searchName.value)|| v.userMail.includes(searchName.value)|| v.userMobile.includes(searchName.value)
    );
      
 
     state.page = 1;   // 切换到第一页
     total.value=tableData.value.length; // 重新设置总数量
 
      /**
       * id search
      let seachid=searchName.value
      console.log("id"+searchName.value)
      let data= UserinfoDataService.get(seachid);
      console.log(data)
 
      UserinfoDataService.get(seachid).then(response=>{    
              console.log("class处理成功情况4");
              console.log(response.data);
              temtable.value=response.data
 
              //tableData.value=response.data;                 
              //router.push('tablebind')
          })
          .catch(error=>{
              console.log(error);
          });
 
          //tableData.value = temtable.value
    */
 
   }
   else
   {
      console.log('empty');
      tableData.value =  temtable.value;  //重新绑定值
      router.push('tablebind');
 
   }
 
  }

  

 

 

posted @   ®Geovin Du Dream Park™  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2018-08-27 PHP7.27: pdf
2012-08-27 Create Ms Word doc using Javascript And vbscript
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示