Simple learning of element-ui + implementation of addition, deletion, modification and query based on springboot
Article directory
-
- Simple learning of element-ui + implementation of addition, deletion, modification and query based on springboot
- Sample demo
- button inside element ui
- The use of element-ui hyperlinks (linked)
- Radio radio button use
- CheckBox
- input input box
- Use of select drop-down box
- Use of Switch components
- Upload our files in upload
- form form
- Add, delete, modify and check (combined with component crud)
- Writing front-end code
- Revise
- Simple learning of element-ui + implementation of addition, deletion, modification and query based on springboot
Sample demo
sprinngbooy+vue implements simple addition, deletion, modification and query (simple front-end and back-end separation)
How to start our vue ui
Our element ui created here is designed.
This is our graphical
ui (graphical interface) (execute our vue ui this is what we want to create)
What we do is that first we create a vue project
After creating it, we need to install our element ui plug-in
This is the plug-in we want to choose
But what we want to delete is the format. Is it important to format our code?
This is quite important
Start the history module
The effect after creation
Then one of our element ui plug-ins has been installed, so we can directly install the plug-in.
Just search and install it
The installation is complete
Start this project next
We open our vue directly in our idea (that is, the vue project we just created), and then use idea
Just open it
Then we just run our commands directly in the idea integrated console.
npm run serve
The picture below is the result of our successful operation.
element -icon provided by ui
That is, a set of commonly used icon components
It’s very simple. We just modify the class name we want and it’s ok.
We can just use their tags
button inside element ui
This is also a set of commonly used operation buttons.
This is the style processing we are going to do. What we can see is this rounded corner plus the weakening of our background.
These effects are plain and round that can be superimposed, and can be superimposed to achieve better effects through our superimposition processing.
Circle is to set our button directly to a circle. This is directly to a circle.
There is also a click event bound to us
That is, we can set whether our icon can be clicked or not.
Set our disabled
The loading attribute can set the loading effect for the button
<el-button type="success" icon="el-icon-check" circle @click="test()" :loading="loading"></el-button>
Here we bind our button attribute to our button. When we click our button, our loading attribute will be bound.
We gave our load attribute our value binding,
//这里就是给我们的代码进行的包装处理 比如说我们的test 以及我们的settimeout就是设置我们的定时开关
<script>
export default {
name: "test",
methods: {
test() {
this.loading = true
setTimeout(()=>{
this.loading=false
},3000)
}
},
data() {
return {
loading: false
}
}
}
</script>
When setting the size of our pictures, we do not set the pixels but set our minus big or something.
Here we can set up our data to be processed from large to small.
The use of element-ui hyperlinks (linked)
Use of link
It’s a file hyperlink
We use the el-linked tag
After the settings are completed, we can directly use this tag to process some data.
When we set our target attribute for it and set its target attribute to blank, an empty page will be opened by default.
Similarly, we can set our disabled attribute to our label so that it cannot be clicked.
underline
This is an operation to set whether our underscore is present or not.
We directly perform attribute binding processing
This icon can also be used to set icons for our text hyperlinks.
We can just make modifications directly in this tag.
Radio radio button use
Just use the label el-radio
Bind data through v-model to bind data objects. Label represents the value of our radio button.
Just write the text directly in the label
<el-radio v-model="radio" label="1">备选项</el-radio>
<el-radio v-model="radio" label="2">备选项</el-radio>
One is a button and the other is a checkbox. There are two options here.
CheckBox
Checkbox
This is taken
el-checkbox tag
Source code analysis: In fact, the process of looping an array is easier to understand.
<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 {
name: "testCheckbox",
data() {
return {
checkAll: false,
checkedCities: ['上海', '北京'],
cities: cityOptions,
isIndeterminate: true
};
},
methods: {
handleCheckAllChange(val) {
this.checkedCities = val ? cityOptions : [];
this.isIndeterminate = false;
},
handleCheckedCitiesChange(value) {
//如果要是不确定某些数据是什么 我们就可以将这个数据打印出来
//在这里我们可以进行的操作就是
//alert(value)//这里就是打印出来我们想要的数据处理 这一点很重要的
let checkedCount = value.length;
this.checkAll = checkedCount === this.cities.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
}
}
}
</script>
<style scoped>
</style>
input input box
controlled components
<el-input v-model="input" placeholder="请输入内容"
></el-input>
<el-button type="primary"@click="click()">一个小按钮</el-button>
You can set our attributes by modifying the attribute large/medium of our input box through our size attribute.
How to modify the size of our input box
Regarding the modified size of this input box, because this is an add-on component, it does not provide us with the modification of this width, so if we want to modify it,
The following methods can be adopted for actual operation processing:
<div style="width: 300px">
<el-row>
<el-input v-model="input" placeholder="请输入内容"
></el-input>
<el-button type="primary" @click="click()">一个小按钮</el-button>
</el-row>
</div>
That is, we achieve this attribute by modifying the style of the div tags nested outside us.
The show-password attribute can be switched
After adding our show-password attribute, we can hide our password
You can switch it yourself
We can also set our pictures
Add our picture (icon) to our input component
prefix-icon and our suffix-icon set the first icon
Display of results:
One of the data here is the limit of our maximum length and the other is what our maximum length is.
Use of select drop-down box
The first is the effect achieved
el-select/el-option
We just use our v-model to bind our data.
Then we use our label to display our text.
value is the value of our current option
<template>
<el-select v-model="value" placeholder="请选择">
<el-option
//进行一个for循环进行遍历渲染我们的数据进入
//从我们的数组里面拿东西
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}, {
value: '选项3',
label: '蚵仔煎'
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}],
value: ''
}
}
}
</script>
Use of Switch components
This represents the switch processing of our two sets of relatively opposite events.
We use el-Switch to process our data
We still use v-model to bind our data.
The switch is used
Using our Boolean type for our switch processing means that our TRUE represents turning on and FALSE represents turning off the attribute.
We can perform actual operations and processing on our Switch data
<el-switch
v-model="value1"
active-color="#13ce66"
active-text="上架"
inactive-color="#ff4949"
inactive-text="下架">
<!--就是这个颜色的值 我们是可以进行改变的 这个是由我们自行决定的 取决于我们自己的操作 如何进行操作 这个都是比较重要的-->
</el-switch>
This active-text="on the shelf" represents the changes we make when we put our Switch on our left side, and then what is our text content when we move it to our right side?
Upload our files in upload
Here we choose a more beautiful code for our actual operation processing.
In this case, we can actually drag our data here directly.
Below is our code
<el-upload
class="upload-demo"
drag
action="https://jsonplaceholder.typicode.com/posts/"
//这个是我们的后端请求的接口
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>
Action is the interface of our backend and will transmit our data to our backend through this interface.
At the backend, we use springboot+easyExcel data for analysis.
Our idea is to put our Excel table into our drag box, and then we parse our data from the background
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
This is the dependency we added in the pom file
2. Create a class to map Excel files
It is the attributes of the class that correspond to this
@Data
public class ExcelVo {
//这个就是我们的实体类
@ExcelProperty("编号")
private Integer id;//我们在这个上边加上我们的注解就可以将我们的数据和Excel里面的数据进行相应的映射处理
@ExcelProperty("姓名")
private String name;
@ExcelProperty("性别")
private String gender;
@ExcelProperty("年龄")
private String age;
@ExcelProperty("班级")
private String classes;
}
Then we create an Excelservice to implement our business logic
The following is what our service layer does
package com.example.test.excelService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.test.entity.ExcelVo;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author yt1105
* @version 1.0
*/
@Service
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);//这个函数里面就是每一次都会将我们的Excel里面的数据解析成为我们的一个实体类
//任何我们放进去就可以
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("数据解析完成");
}
}).doRead();
return list;
}
}
Create controllerExcelcontroller
Receive front-end requests and call Excelservice for data analysis
package com.example.test.ExcelController;
import com.example.test.entity.ExcelVo;
import com.example.test.excelService.ExcelService;
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;
/**
* @author yt1105
* @version 1.0
*/
@RestController
@RequestMapping("/excel")
public class controller {
@Autowired
private ExcelService excelService;
@PostMapping("/import")
public String importDate(@RequestParam("file") MultipartFile file) {
try {
List<ExcelVo> list = this.excelService.list(file.getInputStream());
for (ExcelVo excelvo : list
) {
System.out.println(excelvo);
}
} catch (IOException e) {
return "失败";
}
return "success";
}
}
The problem is that the front-end data cannot be put into the back-end.
The uploaded data cannot be uploaded
Still need further solution
form form
In the Form component, each form field is composed of a Form-Item component. Various types of form controls can be placed in the form field, including Input, Select, Checkbox, Radio, Switch, DatePicker, TimePicker
Various types of form controls can be placed in form fields.
Even what we learned before can be embedded into our form.
The value of the entire form field is directly bound to the vue object.
This is the effect of our demonstration
What we can see is that our data is encapsulated and placed in our form.
What we can use directly is the data we want to pass to the background.
This can also be said to be the binding of our data
Data validation
This is a problem that we will often encounter in our development process, so this is also a problem that we need to master frequently.
So we can further process the data we need
Because once we do not enter our data accurately, we will report an error
The following is our data verification code
Verification of custom data (that is, we decide how to verify the mailbox)
We can define our own regular expressions for verification
Our regular expression is used for verification processing.
var checkEmail = (
rule, value, callback
) => {
const mailReg = /^(?![0-9]+$)(?![a-zA-Z]+$)(?!([^(0-9a-zA-Z)]|[\(\)])+$)([^(0-9a-zA-Z)]|[\(\)]|[a-zA-Z]|[0-9]){6,}$/
if (!value) {
return callback(new Error("邮箱不能为空"))
}
setTimeout(() => {
if (mailReg.test(value)) {
callback();
} else {
callback(new Error("请输入正确的格式"))
}
}, 100)
};
Add, delete, modify and check (combined with component crud)
This is our data sheet
We just perform so-called additions, deletions, modifications and queries on the data in our table.
Let’s first write out the interface of our backend
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.2</version>
</dependency>
One is its own dependence
One is code generation
Automatically generate backend code through mybaits-plus
This automatic code generator is relatively easy to use.
package com.example.test;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* @author yt1105
* @version 1.0
*/
public class Main {
public static void main(String[] args) {
AutoGenerator autoGenerator = new AutoGenerator();
//数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
//后面相当于给我们的数据进行传递参数
dataSourceConfig.setDbType(DbType.MYSQL);//这个就是配置我们的mysql属性
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/yt01?serverTimezone=Asia/Shanghai");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("root");
autoGenerator.setDataSource(dataSourceConfig);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
globalConfig.setAuthor("yt");
globalConfig.setOpen(false);//设置是否将我们的代码打开就是资源管理器打开 我们不需要打开就行
//包的配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.yt");
packageConfig.setEntity("entity");
packageConfig.setMapper("mapper");
packageConfig.setService("service");
packageConfig.setServiceImpl("service.impl");
packageConfig.setController("controller");
autoGenerator.setPackageInfo(packageConfig);
//策略配置
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setInclude("temp");
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setEntityLombokModel(true);
autoGenerator.setStrategy(strategyConfig);//加入我们的配置处理
autoGenerator.execute();
}
}
This shows success
We successfully displayed our data on a page
Similarly, everyone still needs to configure data in their own yml file.
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/yt01?serverTimezone=Asia/Shanghai
username: root
password: root
thymeleaf:
cache: false
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
mapper-locations: classpath:mapper/*.xml
Because we can directly use the code that others gave us
We can directly write the controller layer
Writing front-end code
1. We need an axios plug-in
Select the first option and install it directly.
It’s basically the same operation as installing element ui before.
1. Display of data
We just need to replace our fake data with the data in our data.
What does this mean? Our current data cannot be modified dynamically.
but we can
However, so-called cross-domain problems will occur during the interaction between our front and back ends.
Let's take a look at what that means.
the first we encountered
Our backend code
Front-end domain name
(http://localhost:8080/index01)
We can obviously see that the two port numbers are different, so this is also the key point we need to solve.
Add cross-domain annotations to our backend to solve our cross-domain problems
This is a back-end operation form. Of course, there are also front-end operations, but we won’t solve them one by one here.
I'll just talk about this one method.
This is our data
<template>
<el-table
:data="tableData"
border
style="width: 800px">
<el-table-column
fixed
prop="bookid"
label="编号"
width="150">
</el-table-column>
<el-table-column
prop="name"
label="书名"
width="150">
</el-table-column>
<el-table-column
prop="price"
label="价格"
width="250">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="200">
<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: "index01",
created() {
let _this = this;//由于回调函数 我们不能直接写我们的data对象
axios.get('http://localhost:8081/temp/list').then(function (resp) {
console.log(resp.data)
//然后我们只需要将·我们的这个拿到的数据复制给我们的tabledata
//解决了跨域问题
_this.tableData = resp.data;//这里的话 我们的数据就可以进行一一对应
})
},
methods: {
handleClick(row) {
console.log(row);
}
},
data() {
return {
tableData: ''
//这里我们直接将我们的tabledata设置为null就行,因为这里根本用不到这个数据了 我们是动态的进行传递我们的数据
}
}
}
</script>
<style scoped>
</style>
delete data
This is a function that we use to prompt us to pop up the window designed by element ui. We can use this code directly.
handleClick(row) {
let _this=this;
console.log(row);
},handleDelete(row){
this.$confirm('此操作将永久删除'+row.name+', 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
axios.delete('http://localhost:8081/temp/delete/'+row.bookid).then(function (resp) {
if (resp.data){
_this.$alert('《'+row.name+'》', '提示', {
confirmButtonText: '确定',
callback: action => {
location.reload();
//我们的数据要是加载成功的话 我们就直接重新加载一下我们的页面就行
}
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
}
This is our deletion code, just bind it
Revise
code demo
One of our echoes that is used is our findbyid
When we click our edit button we will jump to a new page
where we make new edits
We can use the interface provided to us by the backend, and then perform the callback function operation to obtain the data we want.
Then the front end can render accordingly.
The key is to pay attention to how to deal with cross-domain issues
Here I adopt the method of adding annotations on the backend to handle our cross-domain issues.
To delete data, just call our backend interface and pass in the ID you want to delete.
As for how the back-end is performed, we don't need to worry about how to implement this bottom layer. That is to say, the front-end does not need to know how the back-end operates our database. At the same time, our back-end has mybaits-plus. As a result, we can directly use the encapsulated code, but in actual development, we cannot rely too much on these things. We must use it wisely.
As for the front-end code, I feel that it is very complicated, with a lot of things that need to be laid out and some data bound.
Then by requesting routing, arranging routing, and setting page jumps, these are all things that front-end students have to do.
It is very important to be proficient in using axios but also to know the principles behind it.
The feeling it gives me is
The operation performed by the front-end students is to call the data passed by the back-end students and then render the data.
Then you can process some pop-up windows, that is, what to do after getting the data. These are front-end students. For example, after clicking this button, what events will be triggered, and then process the subsequent things according to specific needs. .
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
}
这个是我们的删除代码 就是绑定了一下