Element Ul快速入门

  • Element Ul快速入门已关闭评论
  • 141 次浏览
  • A+
所属分类:Web前端
摘要

Element Ul是基于Vue的一套桌面端组件库,提前封装好的Ul模板,方便开发者快速搭建一个网站前端界面


Element Ul快速入门

Element Ul是基于Vue的一套桌面端组件库,提前封装好的Ul模板,方便开发者快速搭建一个网站前端界面

官网:https://element.eleme.cn/

1.Element Ul安装

Element Ul快速入门

Element Ul快速入门

Element Ul快速入门

在插件中,点击添加插件 搜索element

Element Ul快速入门

安装成功,界面如下所示

Element Ul快速入门

如果安装成功,会看到如下界面

Element Ul快速入门

2.Icon图标的使用

<i class="el-icon-edit"></i> <i class="el-icon-delete"></i> <i class="el-icon-phone"></i> 

3.Button按钮

是Element Ul 提供的一组常用的操作按钮组件,直接使用封装好的el-button,比如

 <el-button>按钮</el-button> 

Element Ul快速入门

基于el-button,按钮,可以使用type、plain、round、circle属性对按钮进行修饰。

type:设置按钮的样式

 <el-button>默认按钮</el-button>   <el-button type="primary">主要按钮</el-button>   <el-button type="success">成功按钮</el-button>   <el-button type="info">信息按钮</el-button>   <el-button type="warning">警告按钮</el-button>   <el-button type="danger">危险按钮</el-button> 

plain 可以减弱按钮的背景颜色效果

<el-button type="primary" plain>主要按钮</el-button> 

round 可以给按钮设置圆角

<el-button type="primary" round>主要按钮</el-button> 

circle 将按钮设置为圆形

 <el-button type="primary" icon="el-icon-edit" circle></el-button> 

disabled设置按钮的可以状态

 <el-button type="primary" icon="el-icon-edit "  circle disabled></el-button> 

loading属性可以给按钮设置"加载中"的效果

<template>     <div>         <el-button type="primary" icon="el-icon-edit " circle @click="test()" :loading=loading></el-button>     </div> </template> <script>     export default {         name: "test",         methods:{             test(){               //  alert("11111");                 this.loading = true;                 setTimeout(()=>{                     this.loading = false;                 },3000)             }         },         data(){             return{                 loading:false             }         }     } </script>  <style scoped>  </style> 

size属性可以设置按钮的大小,medium,small,mini

<el-button type="primary" size="medium">主要按钮</el-button> 

Element Ul快速入门

4.Link超链接

文字超链接,使用 el-link标签来实现

<el-link href="https://www.baidu.com" target="_blank">baidu</el-link> target="_blank 可以让页面在新的窗口打开 

disabled 设置超链接不可用

underline设置下划线

​ :underline="false" 来去掉超链接的下划线

icon给文字超链接设置图标

<el-link href="https://www.baidu.com" icon="el-icon-phone-outline" :underline="false"  target="_blank">baidu</el-link> 

5.Radio单选框

使用el-radio标签即可,通过v-model进行对象数据的绑定,label表示该单选框的值,文本直接写入到标签内部即可

<template>   <el-radio v-model="radio" label="1">选项1</el-radio>   <el-radio v-model="radio" label="2">选项2</el-radio> </template>  <script>   export default {     data () {       return {         radio: '1'       };     }   } </script> 

change绑定切换事件

 <el-radio v-model="radio" label="2" @change="change">选项1</el-radio>  <el-radio v-model="radio" label="2" @change="change">选项2</el-radio> 	methods:{             change(){                 console.log('当前radio的值: '+this.radio);             }         }  

6.Checkbox多选框的使用

<template>   <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>   <div style="margin: 15px 0;"></div>   <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">     <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>   </el-checkbox-group> </template> <script>   const cityOptions = ['上海', '北京', '广州', '深圳'];   export default {     data() {       return {         checkAll: false,         checkedCities: ['上海', '北京'],         cities: cityOptions,         isIndeterminate: true       };     },     methods: {       handleCheckAllChange(val) {         this.checkedCities = val ? cityOptions : [];         this.isIndeterminate = false;       },       handleCheckedCitiesChange(value) {         let checkedCount = value.length;         this.checkAll = checkedCount === this.cities.length;         this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;       }     }   }; </script> 

Element Ul快速入门

Element Ul快速入门

7.input输入框

<el-input v-model="input" placeholder="请输入内容"></el-input> <el-button type="success" @click="click">成功按钮</el-button> methods:{                      click(){                 this.input="hello"             } }  data(){             return{                 input:''             }         } 

通过size属性修改输入框的尺寸,large/medium / small / mini,size修改的是输入框的高度

 <el-input v-model="input" size="mini" placeholder="请输入内容"></el-input> 

修改宽度可以在外出嵌套一个div,通过修改div的宽度来实现输入框宽度的修改

<div style="width: 200px">     <el-input v-model="input" size="mini" placeholder="请输入内容"></el-input>           </div> 

Element Ul快速入门

show-password 属性设置可以切换显示隐藏的密码框

通过 prefix-iconsuffix-icon 属性在 input 组件首部和尾部增加显示图标

 <el-input v-model="input" show-password prefix-icon="el-icon-phone" suffix-icon="el-icon-remove" placeholder="请输入内容"></el-input> 

Element Ul快速入门

maxlength、minlength限制输入框的字符长度

show-word-limit //显示输入了几个字符,一共能输入几个字符 <el-input v-model="input" maxlength="6" show-word-limit  placeholder="请输入内容"></el-input> 

Element Ul快速入门

8. Select下拉框

使用el-select/el-option 标签进行操作,v-model进行数据绑定,label进行文本的展示,value是当前选项的值

v-model的值为当前被选中的el-option的 value 属性值 disabled 表示禁止使用 change 下拉框进行修改之后会自动触发该事件(该事件加在el-select中)    <el-select v-model="value" placeholder="请选择" @change="change1">        <el-option             v-for="item in options"             :key="item.value"             :label="item.label"             :value="item.value"             :disabled="item.disabled">       /el-option>   </el-select>  <script>   export default {       methods:{             change1(){                 console.log('当前选择的是:'+this.value)             }       }     data() {       return {         options: [{           value: '选项1',           label: '黄金糕',           disabled:true         }, {           value: '选项2',           label: '双皮奶'         }, {           value: '选项3',           label: '蚵仔煎',           disabled:true         }, {           value: '选项4',           label: '龙须面'         }, {           value: '选项5',           label: '北京烤鸭'         }],         value: ''       }     }   } </script> 

Element Ul快速入门

9.Switch开关

switch组件表示两种相互对立状态之间的切换,开发,el-switch标签完成,v-model进行数据绑定,Boolean表示开/关的状态,active-color属性与inactive-color属性来设置开关的背景色。

active-text属性与inactive-text属性来设置开关的文字描述。

change事件进行开/关操作时触发该方法 <el-switch   v-model="value"   active-color="#13ce66" //打开的颜色   inactive-color="#ff4949"//关闭的颜色   active-text="按月付费" //设置打开的文本   inactive-text="按年付费"   @change="change1">  </el-switch> <script>   export default {     data() {       return {         value: true       }     },   methods:{             change1(){                 console.log('当前开关的状态是:'+this.value)             },          }; </script> 

Element Ul快速入门

10.Upload上传文件

10.1前端

使用el-upload组件完成,action属性为后端请求的接口

        <el-upload                 class="upload-demo"                 drag                 action="http://localhost:8082/excel/import"                 multiple>             <i class="el-icon-upload"></i>             <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>             <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>         </el-upload> 

10.2后端

springboot +easyExcel完成Excel数据的解析

1.pom.xml导入easyExcel相关依赖

   <dependency>             <groupId>com.alibaba</groupId>             <artifactId>easyexcel</artifactId>             <version>2.2.6</version>         </dependency> 

2.创建一个类,用来映射Excel文件

Element Ul快速入门

ExcelVo

package com.example.upload.vo;  import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data;  @Data public class ExcelVo {     @ExcelProperty("标号")     private Integer id;          @ExcelProperty("姓名")     private String name;          @ExcelProperty("性别")     private String gender;          @ExcelProperty("年龄")     private String age;          @ExcelProperty("班级")     private String classes;      }  

ExcelService

package com.example.upload.service;  import com.example.upload.vo.ExcelVo;  import java.io.InputStream; import java.util.List;  public interface ExcelService {     public List<ExcelVo> list(InputStream inputStream); }  

ExcelServiceimpl

package com.example.upload.service.impl;  import com.alibaba.excel.EasyExcel; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.example.upload.service.ExcelService; import com.example.upload.vo.ExcelVo;  import java.io.InputStream; import java.util.ArrayList; import java.util.List;  public class ExcelServiceimpl implements ExcelService {      @Override     public List<ExcelVo> list(InputStream inputStream) {         List<ExcelVo> list = new ArrayList<>();         EasyExcel.read(inputStream)                 .head(ExcelVo.class)                 .sheet()                 .registerReadListener(new AnalysisEventListener<ExcelVo>() {                       @Override                     public void invoke(ExcelVo excelVo, AnalysisContext analysisContext) {                         list.add(excelVo);                     }                      @Override                     public void doAfterAllAnalysed(AnalysisContext analysisContext) {                         System.out.println("数据解析完成");                     }                 }).doRead();          return list;     } }  

ExcelController

package com.example.upload.controller;  import com.example.upload.service.ExcelService; import com.example.upload.vo.ExcelVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;  import java.io.IOException; import java.util.List;  @RestController @RequestMapping("/excel") public class ExcelController {     @Autowired     private ExcelService excelService;     @PostMapping("/import")     public String importData(@RequestParam("file")MultipartFile file){        try {            List<ExcelVo> list = excelService.list(file.getInputStream());            for (ExcelVo excelVo:list){                System.out.println(excelVo);            }        } catch (IOException e) {            return "false";        }     return  "success";    }  }  

需要解决跨域问题

CorsConfig

package com.example.upload.config;  import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  @Configuration public class CorsConfig implements WebMvcConfigurer {     @Bean     public WebMvcConfigurer corsConfigurer() {         return new WebMvcConfigurer() {             @Override             public void addCorsMappings(CorsRegistry registry) {                 registry.addMapping("/**")                         .allowCredentials(false)                         .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")                         .allowedOrigins("*");             }         };     } }  

示例:

Element Ul快速入门

11.Form表单

Form组件,每一个表单域由一个el-form-item组件构成的,表单域中可以放置各种类型的表单控件,input、select、CheckBox、radio、switch,表单域的的值直接跟Vue对象进行绑定

11.1基本使用

<el-form ref="form" :model="form" label-width="80px">   <el-form-item label="活动名称">     <el-input v-model="form.name"></el-input>   </el-form-item>   <el-form-item label="活动区域">     <el-select v-model="form.region" placeholder="请选择活动区域">       <el-option label="区域一" value="shanghai"></el-option>       <el-option label="区域二" value="beijing"></el-option>     </el-select>   </el-form-item>   <el-form-item label="活动时间">     <el-col :span="11">       <el-date-picker type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker>     </el-col>     <el-col class="line" :span="2">-</el-col>     <el-col :span="11">       <el-time-picker placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker>     </el-col>   </el-form-item>   <el-form-item label="即时配送">     <el-switch v-model="form.delivery"></el-switch>   </el-form-item>   <el-form-item label="活动性质">     <el-checkbox-group v-model="form.type">       <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>       <el-checkbox label="地推活动" name="type"></el-checkbox>       <el-checkbox label="线下主题活动" name="type"></el-checkbox>       <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>     </el-checkbox-group>   </el-form-item>   <el-form-item label="特殊资源">     <el-radio-group v-model="form.resource">       <el-radio label="线上品牌商赞助"></el-radio>       <el-radio label="线下场地免费"></el-radio>     </el-radio-group>   </el-form-item>   <el-form-item label="活动形式">     <el-input type="textarea" v-model="form.desc"></el-input>   </el-form-item>   <el-form-item>     <el-button type="primary" @click="onSubmit">立即创建</el-button>     <el-button>取消</el-button>   </el-form-item> </el-form> <script>   export default {     data() {       return {         form: {           name: '',           region: '',           date1: '',           date2: '',           delivery: false,           type: [],           resource: '',           desc: ''         }       }     },     methods: {       onSubmit() {         console.log(this.form);       }     }   } </script> 

Element Ul快速入门

11.2数据效验

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

<template>     <div>          <el-form ref="form" :model="form" :rules="rules"  label-width="80px">             <el-form-item label="活动名称" prop="name">                 <el-input v-model="form.name"></el-input>             </el-form-item>             <el-form-item label="活动区域"  prop="region" >                 <el-select v-model="form.region" placeholder="请选择活动区域">                     <el-option label="区域一" value="shanghai"></el-option>                     <el-option label="区域二" value="beijing"></el-option>                 </el-select>             </el-form-item>             <el-form-item label="活动时间" >                 <el-col :span="11">                     <el-date-picker type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker>                 </el-col>                 <el-col class="line" :span="2">-</el-col>                 <el-col :span="11">                     <el-time-picker placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker>                 </el-col>             </el-form-item>             <el-form-item>                 <el-button type="primary"   @click="submitForm('form')">立即创建</el-button>                 <el-button>取消</el-button>             </el-form-item>         </el-form>     </div>  </template>  <script>      export default {         name: "test",         methods: {             submitForm(formName) {                 this.$refs[formName].validate((valid) => {                     if (valid) {                         alert('submit!');                     } else {                         console.log('error submit!!');                         return false;                     }                 });             }          },         data() {             return {                 form: {                     name: '',                     region: '',                     date1: '',                     date2: ''                 },                 rules: {                     name: [                         { required: true, message: '请输入活动名称', trigger: 'blur' },                         { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }                     ],                     region: [                         { required: true, message: '请选择活动区域', trigger: 'change' }                     ],                     date1: [                         { type: 'date', required: true, message: '请选择日期', trigger: 'change' }                     ],                     date2: [                         { type: 'date', required: true, message: '请选择时间', trigger: 'change' }                     ],                  }              }          }     } </script>  <style scoped>  </style> 

Element Ul快速入门

11.3自定义数据效验(邮箱效验)

邮箱效验的正则表达式

const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/

<template>     <div style="width: 500px">          <el-form ref="form" :model="form" :rules="rules"  label-width="80px">             <el-form-item label="邮箱" prop="email">                 <el-input v-model="form.email"></el-input>             </el-form-item>               <el-form-item>                 <el-button type="primary"   @click="submitForm('form')">立即创建</el-button>                 <el-button>取消</el-button>             </el-form-item>         </el-form>     </div>  </template>  <script>      export default {         name: "test",         methods: {             submitForm(formName) {                 this.$refs[formName].validate((valid) => {                     if (valid) {                         //alert('submit!');                         alert(this.form.email)                     } else {                         //console.log('error submit!!');                         alert("error submit")                         return false;                     }                 });             }          },         data() {             var checkEmail = (rule,value,callback)=>{                 //const mailReg = /^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$/                 const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/                 if (!value){                     return callback(new Error('邮箱不能为空'))                 }                 setTimeout(()=>{                     if (mailReg.test(value)){                         callback()                     }else{                         callback(new Error('请输入正确的邮箱格式'))                     }                 },100)             }             return {                 form: {                     email: '',                  },                 rules: {                     email: [                         { required: true,validator:checkEmail , trigger: 'blur' },                      ]                  }              }          }     } </script>  <style scoped>  </style> 

Element Ul快速入门

Element Ul快速入门

11.4数字类型效验

数字类型的验证需要在 v-model 处加上 .number 的修饰符,这是 Vue 自身提供的用于将绑定值转化为 number 类型的修饰符。

<template>     <div style="width: 500px">          <el-form ref="form" :model="form" :rules="rules"  label-width="80px">             <el-form-item label="年龄" prop="age"                 :rules="[                     { required: true, message: '年龄不能为空',  },                     { type:'number', message: '年龄必须为数字值', trigger: 'blur' }                 ]">                 <el-input v-model.number="form.age"></el-input>             </el-form-item>              <el-form-item>                 <el-button type="primary"   @click="submitForm('form')">立即创建</el-button>                 <el-button>取消</el-button>             </el-form-item>         </el-form>     </div>  </template>  <script>      export default {         name: "test",         methods: {             submitForm(formName) {                 this.$refs[formName].validate((valid) => {                     if (valid) {                         alert(this.form.age)                     } else {                         alert("error submit")                         return false;                     }                 });             }          },         data() {             return {                 form: {                     age: '',                }             }         }     } </script> <style scoped> </style> 

Element Ul快速入门

Element Ul快速入门

12.CRUD小案例

1.数据库

Element Ul快速入门

2.后端

1.在pom.xml添加mybatis plus相关依赖

  <dependency>             <groupId>com.baomidou</groupId>             <artifactId>mybatis-plus-boot-starter</artifactId>             <version>3.4.3</version>         </dependency>         <dependency>             <groupId>com.baomidou</groupId>             <artifactId>mybatis-plus-generator</artifactId>             <version>3.3.2</version>         </dependency>         <dependency>             <groupId>org.apache.velocity</groupId>             <artifactId>velocity</artifactId>             <version>1.7</version>         </dependency> 

2.application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=123456 

在启动类(Application)中指定mapper的位置

@MapperScan("com.example.upload.mapper") 

3.LianxiController

package com.example.upload.controller;   import com.example.upload.entity.Lianxi; import com.example.upload.service.LianxiService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;  import org.springframework.stereotype.Controller;  import java.util.List;  /**  * <p>  *  前端控制器  * </p>  *  * @author southwind  * @since 2023-01-03  */ @RestController @RequestMapping("/lianxi") public class LianxiController {      @Autowired     private LianxiService lianxiService;      @GetMapping("/list")     public List<Lianxi> list(){         return this.lianxiService.list();     } /* 一般来讲的话是以两种方式为主,分别为Post和Get,这两种方式都是向一个url传参,而Get方式体现到了地址栏里,Post方式则将内容放在了 body 里面。 @PathParam 和 @PathVariable 注解是用于从 request 中接收请求的,两个都可以接收参数,关键点不同的是@PathParam 是从 request 里面拿取值, 而 @PathVariable 是从一个url模板里面来填充(绑定 URL 占位符到功能处理方法的参数上,主要实现RESTFULL风格的请求),也就是从地址栏中取值(以键值对形式)。 @PathVariable 它是以“/”方式来获取参数值。  */     @GetMapping("/findById/{id}")     public Lianxi findById(@PathVariable("id") Integer id){         return this.lianxiService.getById(id);     }      @DeleteMapping("/delete/{id}")     public boolean delete(@PathVariable("id") Integer id){         return this.lianxiService.removeById(id);     }      //RequestBody是把json格式字符串串 ,转换为java类型的     @PostMapping("/add")     public boolean add(@RequestBody Lianxi lianxi){         return  this.lianxiService.save(lianxi);     }      @PutMapping("/update")     public boolean update(@RequestBody Lianxi lianxi){         return  this.lianxiService.updateById(lianxi);     } }   

3.前端

1.安装axios插件

Element Ul快速入门

2.首页数据加载

Element Ul快速入门

<template>     <el-table             :data="tableData"             border             style="width: 650px">         <el-table-column                 fixed                 prop="bookid"                 label="编号"                 width="130">         </el-table-column>         <el-table-column                 prop="name"                 label="书名"                 width="170">         </el-table-column>         <el-table-column                 prop="price"                 label="价格"                 width="120">         </el-table-column>         <el-table-column                 fixed="right"                 label="操作"                 width="180">             <template slot-scope="scope">                 <el-button                         size="mini"                         @click="handleEdit(scope.$index, scope.row)">编辑</el-button>                 <el-button                         size="mini"                         type="danger"                         @click="handleDelete(scope.$index, scope.row)">删除</el-button>             </template>         </el-table-column>     </el-table> </template>  <script>     export default {         name: "Index",         created() {             let  _this = this;             axios.get('http://localhost:9000/lianxi/list').then(function (resp) {                   //alert(resp.data[0].name);                     // console.log(resp.data)                 _this.tableData = resp.data;             })         },         methods:{             handleClick(row) {                 console.log(row);             }         },         data() {             return {                 tableData: []             }         }      } </script>  <style scoped>  </style> 

3.删除数据

<template>     <el-table             :data="tableData"             border             style="width: 650px">         <el-table-column                 fixed                 prop="bookid"                 label="编号"                 width="130">         </el-table-column>         <el-table-column                 prop="name"                 label="书名"                 width="170">         </el-table-column>         <el-table-column                 prop="price"                 label="价格"                 width="120">         </el-table-column>         <el-table-column                 fixed="right"                 label="操作"                 width="180">             <template slot-scope="scope">                 <el-button                         size="mini"                         @click="handleEdit(scope.row)">编辑</el-button>                      <!-- scope.row 指一行的数据-->                 <el-button                         size="mini"                         type="danger"                         @click="handleDelete(scope.row)">删除</el-button>             </template>         </el-table-column>     </el-table> </template>  <script>     export default {         name: "Index",         created() {             let  _this = this;             axios.get('http://localhost:9000/lianxi/list').then(function (resp) {                   //alert(resp.data[0].name);                     // console.log(resp.data)                 _this.tableData = resp.data;             })         },         methods:{             handleDelete(row) {                 let  _this = this;                  //console.log(row.name);                 this.$confirm('是否确定删除《'+row.name+'》?', '提示', {                     confirmButtonText: '确定',                     cancelButtonText: '取消',                     type: 'warning'                 }).then(() => {                     axios.delete('http://localhost:9000/lianxi/delete/'+row.bookid).then(function (resp) {                         if (resp.data){                             _this.$alert('《'+row.name+'》 删除成功', '提示', {                                 confirmButtonText: '确定',                                 callback: action => {                                     //重新加载一下页面                                     location.reload();                                 }                             });                         }                     })                 }).catch(() => {                    /* this.$message({                         type: 'info',                         message: '已取消删除'                     });*/                 });             }         },         data() {             return {                 tableData: []             }         }      } </script>  <style scoped>  </style> 

4.修改数据

index.vue

<template>     <el-table             :data="tableData"             border             style="width: 650px">         <el-table-column                 fixed                 prop="bookid"                 label="编号"                 width="130">         </el-table-column>         <el-table-column                 prop="name"                 label="书名"                 width="170">         </el-table-column>         <el-table-column                 prop="price"                 label="价格"                 width="120">         </el-table-column>         <el-table-column                 fixed="right"                 label="操作"                 width="180">             <template slot-scope="scope">                 <el-button                         size="mini"                         @click="handleEdit(scope.row)">编辑</el-button>                      <!-- scope.row 指一行的数据-->                 <el-button                         size="mini"                         type="danger"                         @click="handleDelete(scope.row)">删除</el-button>             </template>         </el-table-column>     </el-table> </template>  <script>     export default {         name: "Index",         created() {             let  _this = this;             axios.get('http://localhost:9000/lianxi/list').then(function (resp) {                   //alert(resp.data[0].name);                     // console.log(resp.data)                 _this.tableData = resp.data;             })         },         methods:{             handleEdit(row){                 //把id传给update页面                 this.$router.push('/update?id='+row.bookid)             },             handleDelete(row) {                 let  _this = this;                  //console.log(row.name);                 this.$confirm('是否确定删除《'+row.name+'》?', '提示', {                     confirmButtonText: '确定',                     cancelButtonText: '取消',                     type: 'warning'                 }).then(() => {                     axios.delete('http://localhost:9000/lianxi/delete/'+row.bookid).then(function (resp) {                         if (resp.data){                             _this.$alert('《'+row.name+'》 删除成功', '提示', {                                 confirmButtonText: '确定',                                 callback: action => {                                     //重新加载一下页面                                     location.reload();                                 }                             });                         }                     })                 }).catch(() => {                    /* this.$message({                         type: 'info',                         message: '已取消删除'                     });*/                 });             }         },         data() {             return {                 tableData: []             }         }      } </script> <style scoped> </style> 

update.vue

<template>     <el-form ref="form" :model="form" :rules="rules"  label-width="80px">            <el-form-item label="编号" prop="bookid"                       :rules="[                     { required: true, message: '编号不能为空',  },                     { type:'number', message: '编号不能为数字' }                 ]">                <el-input v-model.number="form.bookid" readonly></el-input>            </el-form-item>         <el-form-item label="书名" prop="name">             <el-input v-model="form.name"></el-input>         </el-form-item>         <el-form-item label="价格" prop="price"                       :rules="[                     { required: true, message: '价格不能为空',  },                     { type:'number', message: '价格不能为数字' }                 ]">             <el-input v-model.number="form.price"></el-input>         </el-form-item>          <el-form-item>             <el-button type="primary"   @click="submitForm('form')">立即修改</el-button>             <el-button>取消</el-button>         </el-form-item>     </el-form> </template>  <script>     export default {         name: "Update",         created() {             let _this = this;             //this.$route.query.id可以用来接收点击编辑传过来的id             axios.get('http://localhost:9000/lianxi/findById/'+this.$route.query.id).then(function (resp){                // console.log(resp.data);                 _this.form = resp.data;             })         },         data(){          return {              form: {                  bookid: '',                  name: '',                  price: ''               },              rules: {                  name: [                      { required: true,message:'请输入图书名称' , trigger: 'blur' },                      {min:3,max:20,message: '长度在3 到20 个字符',trigger: 'blur' }                  ]               }          }      },         methods:{             submitForm(formName) {                 let _this = this;                 this.$refs[formName].validate((valid) => {                     if (valid) {                         //console.log(this.form);                         axios.put('http://localhost:9000/lianxi/update',this.form).then(function (resp) {                             if (resp.data){                                 _this.$alert('《'+_this.form.name+'》 修改成功', '提示', {                                     confirmButtonText: '确定',                                     callback: action => {                                         _this.$router.push('/index')                                     }                                 });                             }                         })                     } else {                         alert("error submit")                         return false;                     }                 });             }         }     } </script> <style scoped> </style> 

5.添加数据

<template>     <el-form ref="form" :model="form" :rules="rules"  label-width="80px">         <el-form-item label="编号" prop="bookid"                       :rules="[                     { required: true, message: '编号不能为空',  },                     { type:'number', message: '编号不能为数字' }                 ]">             <el-input v-model.number="form.bookid" ></el-input>         </el-form-item>         <el-form-item label="书名" prop="name">             <el-input v-model="form.name"></el-input>         </el-form-item>         <el-form-item label="价格" prop="price"                       :rules="[                     { required: true, message: '价格不能为空',  },                     { type:'number', message: '价格不能为数字' }                 ]">             <el-input v-model.number="form.price"></el-input>         </el-form-item>          <el-form-item>             <el-button type="primary"   @click="submitForm('form')">添加</el-button>             <el-button>取消</el-button>         </el-form-item>     </el-form> </template>  <script>     export default {         name: "Add",         data(){             return {                 form: {                     bookid: '',                     name: '',                     price: ''                  },                 rules: {                     name: [                         { required: true,message:'请输入图书名称' , trigger: 'blur' },                         {min:3,max:20,message: '长度在3 到20 个字符',trigger: 'blur' }                     ]                  }             }         },         methods:{             submitForm(formName) {                 let _this = this;                 this.$refs[formName].validate((valid) => {                     if (valid) {                         //console.log(this.form);                         axios.post('http://localhost:9000/lianxi/add',this.form).then(function (resp) {                             if (resp.data){                                 _this.$alert('《'+_this.form.name+'》 添加成功', '提示', {                                     confirmButtonText: '确定',                                     callback: action => {                                         _this.$router.push('/index')                                     }                                 });                             }                         })                     } else {                         alert("error submit")                         return false;                     }                 });             }         }     } </script> <style scoped> </style> 

Element Ul快速入门