What is Element UI
- Element, a set of desktop component library based on Vue 2.0 for developers, designers and product managers
- The Element # UI is based on Vue 2.0
- Element UI provides a set of components
- Element UI provides reference instances of components, which can be copied directly
- Official website:
https://element.eleme.cn/#/zh-CN/component/installation
Build environment
Create project
Step 1: create a project through Vue cli
vue create eui01
Step 2: run the project
Integration 1: plug in
After installing the vue project, enter the project directory and execute the command
vue add element
Integration step 1: determine the import method (import all, import on demand)
integration
Integration 2: installing the element UI plug-in
npm i element-ui --save
Integration: element UI introduction
- The official provides two ways of introduction: complete introduction and on-demand introduction
- Complete introduction: it introduces all components of eui, which are commonly used in learning / development
- Import on demand: import required components for use in production environment.
- Complete introduction
- 1. Import element ui component library
- 2. Import element ui css Style
- Register VUI. element 3
/* Import element UI style */ import 'element-ui/lib/theme-chalk/index.css' import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' /* element-ui All components */ import ElementUI from 'element-ui' Vue.use(ElementUI) Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
3. Layout container
Layout container
- Use the layout container of element UI for page layout. Divide the page (up, down, left and center)
- Official documents: https://element.eleme.cn/#/zh-CN/component/container
The container component used for layout is convenient to quickly build the basic structure of the page:
< El container >: outer container. When the child element contains < El header > or < El footer >, all child elements will be arranged vertically up and down, otherwise they will be arranged horizontally left and right.
< El header >: top bar container.
< El aside >: sidebar container.
< El main >: main area container.
< El footer >: bottom bar container.
The above components adopt flex layout. Please make sure whether the target browser is compatible before use. In addition, the child element of < El container > can only be the last four, and the parent element of the last four can only be < El container >.
Step 1: modify Src / main JS import element UI styles and components
/* Import element UI style */ import 'element-ui/lib/theme-chalk/index.css' import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' /* element-ui All components */ import ElementUI from 'element-ui' Vue.use(ElementUI) Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
Step 2: delete Src / APP Vue all content, copy layout template and style
<template> <div id="app"> <el-container> <el-header>Header</el-header> <el-main>Main</el-main> <el-footer>Footer</el-footer> </el-container> </div> </template> <script> export default { } </script> <style> /* Delete later */ .el-header, .el-footer { background-color: #B3C0D1; color: #333; text-align: center; line-height: 60px; } </style>
reset.css
After the layout page is completed, there will be a circle of blank space in the whole body. Generally, you choose to reset the page style during development
Step 1: Baidu search "reset CSS "and create assets / APP CSS, copy style (copy the following style)
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,th,td { margin: 0; padding: 0; } table { border-collapse: collapse; border-spacing: 0; } fieldset,img { border: 0; } address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } ol,ul { list-style: none; } caption,th { text-align: left; } h1,h2,h3,h4,h5,h6 { font-size: 100%; font-weight: normal; }
Full screen filling
On app Vue, add style
html, body, .el-container { height: 100%; }
4. Navigation bar
demand
Navigation bar
Use navmenu to complete the navigation bar effect
Official documents: https://element.eleme.cn/#/zh-CN/component/menu
<template> <div id="app"> <el-container> <el-header> <!-- Navigation bar --> <el-menu :default-active="$route.path" class="el-menu-demo" mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" > <el-menu-item index="/">home page</el-menu-item> <el-submenu index="2"> <template slot="title">Student management</template> <el-menu-item index="/studentList">Student list</el-menu-item> </el-submenu> <el-submenu index="3"> <template slot="title">Personal Center</template> <el-menu-item index="/login">Sign in</el-menu-item> <el-menu-item index="/register">register</el-menu-item> </el-submenu> <el-menu-item index="/cart"> Shopping Cart </el-menu-item> </el-menu> </el-header> <el-main> <router-view></router-view> </el-main> <el-footer> Copyright 2006 - 2022 College of communication and intelligence </el-footer> </el-container> </div> </template> <script> export default { } </script> <style> .el-header, .el-footer { background-color: #B3C0D1; color: #333; text-align: center; line-height: 60px; padding: 0; } </style>
route
Click "home" and "shopping cart" to adjust the page
Step 1: modify Src / APP Vue set routing view
<template> <div id="app"> <el-container> <el-header> <!-- Navigation bar --> <el-menu class="el-menu-demo" mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" :router="true" > <el-menu-item index="/">home page</el-menu-item> <el-submenu index="2"> <template slot="title">Student management</template> <el-menu-item index="/studentList">Student list</el-menu-item> </el-submenu> <el-submenu index="3"> <template slot="title">Personal Center</template> <el-menu-item index="/login">Sign in</el-menu-item> <el-menu-item index="/register">register</el-menu-item> </el-submenu> <el-menu-item index="/cart"> Shopping Cart </el-menu-item> </el-menu> </el-header> <el-main> <router-view></router-view> </el-main> <el-footer> Copyright 2006 - 2020 College of communication and intelligence </el-footer> </el-container> </div> </template> <script> export default { } </script> <style> .el-header, .el-footer { background-color: #B3C0D1; color: #333; text-align: center; line-height: 60px; padding: 0; } </style>
Step 2: write test components (Home.vue and Cart.vue)
Page refresh navigation selection problem
Default: the default effect after clicking
Refresh the page and the selected state of the navigation bar disappears
Repair: modify app Vue page
<template> <div id="app"> <el-container> <el-header> <!-- Navigation bar --> <el-menu :default-active="$route.path" class="el-menu-demo" mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" :router="true" >
header
<el-footer> Copyright 2006 - 2022 College of communication and intelligence </el-footer>
5. Table: query list
Test page
Basic table
<template> <div> <!-- list --> <el-table :data="studentList" > <el-table-column prop="sid" label="number" width="150"></el-table-column> <el-table-column prop="sname" label="full name" width="150"></el-table-column> <el-table-column prop="gender" label="Gender" width="150"></el-table-column> <el-table-column prop="age" label="Age" width="150"></el-table-column> </el-table> </div> </template> <script> export default { data () { return { studentList: [ { sid: 's001', sname: 'Zhang San', gender: 'male', age: 18 }, { sid: 's002', sname: 'Li Si', gender: 'female', age: 21 } ] } } } </script> <style> </style>
Table decoration
<template> <div> <!-- list --> <el-table :data="studentList" stripe border > <el-table-column prop="sid" label="number" width="150"></el-table-column>
Multiple choice
<template> <div> <!-- list --> <el-table :data="studentList" stripe border @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column prop="sid" label="number" width="150"></el-table-column> <el-table-column prop="sname" label="full name" width="150"></el-table-column> <el-table-column prop="gender" label="Gender" width="150"></el-table-column> <el-table-column prop="age" label="Age" width="150"></el-table-column> </el-table> </div> </template> <script> export default { methods: { handleSelectionChange(val) { this.multipleSelection = val; //Save selected data } }, data () { return { multipleSelection: [], //Multiple selection, selected data studentList: [ { sid: 's001', sname: 'Zhang San', gender: 'male', age: 18 }, { sid: 's002', sname: 'Li Si', gender: 'female', age: 21 } ] } } } </script> <style> </style>
Custom template
<template> <div> <!-- list --> <el-table :data="studentList" stripe border @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column prop="sid" label="number" width="150"></el-table-column> <el-table-column prop="sname" label="full name" width="150"></el-table-column> <el-table-column prop="gender" label="Gender" width="150"></el-table-column> <el-table-column prop="age" label="Age" width="150"></el-table-column> <el-table-column label="operation"> <template slot-scope="scope"> <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">edit</el-button> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">delete</el-button> </template> </el-table-column> </el-table> </div> </template> <script> export default { methods: { handleSelectionChange(val) { this.multipleSelection = val; //Save selected data }, handleEdit(index, row) { console.log(index, row); }, handleDelete(index, row) { console.log(index, row); } }, data () { return { multipleSelection: [], //Multiple selection, selected data studentList: [ { sid: 's001', sname: 'Zhang San', gender: 'male', age: 18 }, { sid: 's002', sname: 'Li Si', gender: 'female', age: 21 } ] } } } </script> <style> </style>
- Exercise: display "hobby" information
studentList: [ { sid: 's001', sname: 'Zhang San', gender: 'male', age: 18, hobbies: ['smoking','drink','Hot head'] }, { sid: 's002', sname: 'Li Si', gender: 'female', age: 21, hobbies: ['smoking','Hot head'] } ]
<template> <div> <!-- list --> <el-table :data="studentList" stripe border @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column prop="sid" label="number" width="150"></el-table-column> <el-table-column prop="sname" label="full name" width="150"></el-table-column> <el-table-column prop="gender" label="Gender" width="150"></el-table-column> <el-table-column prop="age" label="Age" width="150"></el-table-column> <el-table-column label="hobby" > <template slot-scope="scope"> <el-tag type="warning" v-for="(hobby,index) in scope.row.hobbies" :key="index">{{hobby}}</el-tag> </template> </el-table-column> <el-table-column label="operation"> <template slot-scope="scope"> <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">edit</el-button> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">delete</el-button> </template> </el-table-column> </el-table> </div> </template> <script> export default { methods: { handleSelectionChange(val) { this.multipleSelection = val; //Save selected data }, handleEdit(index, row) { console.log(index, row); }, handleDelete(index, row) { console.log(index, row); } }, data () { return { multipleSelection: [], //Multiple selection, selected data studentList: [ { sid: 's001', sname: 'Zhang San', gender: 'male', age: 18, hobbies: ['smoking','drink','Hot head'] }, { sid: 's002', sname: 'Li Si', gender: 'female', age: 21, hobbies: ['smoking','Hot head'] } ] } } } </script> <style> .el-tag + .el-tag { margin-left: 10px; } </style>
summary
label | describe | attribute | describe |
<el-table> | Used to draw tables | data | Data to be displayed |
stripe | Create a zebra striped table | ||
border | Bordered table | ||
<el-table-column> | Used to set the columns of the table | label | Listing |
prop | Key name in corresponding object | ||
width | Column width | ||
type | selection box | ||
<template slot-scope="scope"> | Content embedding, scope |
Condition query
<!-- Condition form start --> <el-form :inline="true" :model="studentVo" size="mini" class="demo-form-inline"> <el-form-item label="class"> <el-select v-model="studentVo.cid" placeholder="Please select a class"> <el-option label="Java12 class" value="c001"></el-option> <el-option label="Java34 class" value="c002"></el-option> </el-select> </el-form-item> <el-form-item label="full name"> <el-input v-model="studentVo.name" placeholder="Please enter your name"></el-input> </el-form-item> <el-form-item label="Age"> <el-col :span="11"> <el-input v-model="studentVo.startAge" placeholder="Please enter the starting age"></el-input> </el-col> <el-col class="line" :span="2">-</el-col> <el-col :span="11"> <el-input v-model="studentVo.endAge" placeholder="Please enter the end age"></el-input> </el-col> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">query</el-button> </el-form-item> </el-form> <!-- Condition form end -->
Paging bar
<!-- Paging bar start --> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.pageNum" :page-sizes="[1, 2, 5, 10]" :page-size="pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total"> </el-pagination> <!-- Paging bar end -->
6. form
Simple form: Login
Display the login page: login vue
Login form effect
<template> <el-card class="box-card"> <el-form :model="user" label-width="80px" ref="loginFormRef"> <el-form-item label="user name"> <el-input v-model="user.username" prefix-icon="el-icon-user" placeholder="enter one user name"></el-input> </el-form-item> <el-form-item label="password"> <el-input v-model="user.password" prefix-icon="el-icon-lock" type="password" placeholder="Please input a password"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="login">Sign in</el-button> <el-button type="info" @click="$refs.loginFormRef.resetFields()" >Reset</el-button> </el-form-item> </el-form> </el-card> </template> <script> export default { data() { return { user: { username: '', password: '' } } }, } </script> <style> .box-card { width: 480px; } </style>
Complex forms: Registration
<template> <el-card class="box-card"> <el-form :model="user" label-width="80px" ref="loginFormRef"> <el-form-item label="user name"> <el-input v-model="user.username" prefix-icon="el-icon-user" placeholder="enter one user name"></el-input> </el-form-item> <el-form-item label="password"> <el-input v-model="user.password" prefix-icon="el-icon-lock" type="password" placeholder="Please input a password"></el-input> </el-form-item> <el-form-item label="Confirm password"> <el-input v-model="user.repassword" prefix-icon="el-icon-lock" type="password" placeholder="Please enter the password again"></el-input> </el-form-item> <el-form-item label="birthday"> <el-date-picker v-model="user.birthday" type="date" placeholder="Select date"> </el-date-picker> </el-form-item> <el-form-item label="education"> <el-select v-model="user.edu" placeholder="Please choose your education"> <el-option label="a reception class" value="xb"></el-option> <el-option label="middle shift" value="zb"></el-option> <el-option label="Big class" value="db"></el-option> <el-option label="Preschool" value="xqb"></el-option> </el-select> </el-form-item> <el-form-item label="Gender"> <el-radio-group v-model="user.gender"> <el-radio label="male"></el-radio> <el-radio label="female"></el-radio> </el-radio-group> </el-form-item> <el-form-item label="hobby"> <el-checkbox-group v-model="user.hobbies"> <el-checkbox label="smoking" name="type"></el-checkbox> <el-checkbox label="drink" name="type"></el-checkbox> <el-checkbox label="Hot head" name="type"></el-checkbox> <el-checkbox label="disco dancing" name="type"></el-checkbox> </el-checkbox-group> </el-form-item> <el-form-item label="marriage "> <el-switch v-model="user.marry"></el-switch> </el-form-item> <el-form-item label="Province, city and county"> <el-cascader v-model="user.city" :options="cityList" ></el-cascader> </el-form-item> <el-form-item> <el-button type="primary" @click="login">Sign in</el-button> <el-button type="info" @click="$refs.loginFormRef.resetFields()" >Reset</el-button> </el-form-item> </el-form> </el-card> </template> <script> export default { data() { return { user: { username: 'jack', password: '1234', repassword: '1234', birthday: '2020-10-07', edu: 'db', gender: 'female', hobbies: ['smoking','Hot head'], marry: true, city: ['jiangsu', 'suqian', 'shuyang'], }, cityList: [ { value: 'jiangsu', label: 'Jiangsu', children: [ { value: 'suqian', label: 'Suqian', children: [ { value: 'shuyang', label: 'Shuyang', }, { value: 'siyang', label: 'Siyang', } ] }, { value: 'lianyungang', label: 'Lianyungang', } ] } ] } }, methods: { login() { alert('Logging in...') } }, } </script> <style> .box-card { width: 480px; } </style>
Form verification
Set verification rules and determine verification attributes
Write verification rules
rules: { Verification properties: [ Rule 1, Rule 2, .... ] }
{ required: true, message: 'enter one user name', trigger: 'blur' }, { min: 3, max: 5, message: `User name length must be 3-5 between`, trigger: 'blur' }
Check when submitting the form
<template> <el-card class="box-card"> <el-form :model="user" :rules="rules" label-width="80px" ref="loginFormRef"> <el-form-item label="user name" prop="username"> <el-input v-model="user.username" prefix-icon="el-icon-user" placeholder="enter one user name"></el-input> </el-form-item> <el-form-item label="password" prop="password"> <el-input v-model="user.password" prefix-icon="el-icon-lock" type="password" placeholder="Please input a password"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="login">Sign in</el-button> <el-button type="info" @click="$refs.loginFormRef.resetFields()" >Reset</el-button> </el-form-item> </el-form> </el-card> </template> <script> export default { data() { return { user: { username: '', password: '' }, rules: { username: [ { required: true, message: 'enter one user name', trigger: 'blur' }, { min: 3, max: 5, message: `User name length must be 3-5 between`, trigger: 'blur' } ], password: [ { required: true, message: 'Please input a password', trigger: 'blur' }, { min: 3, max: 5, message: `Password length must be 3-5 between`, trigger: 'blur' } ] } } }, methods: { login() { this.$refs.loginFormRef.validate(valid => { if(valid) { // Verification passed console.info('adopt') } else { // Verification failed console.info('Fail') } }) } }, } </script> <style> .box-card { width: 480px; } </style>
Custom verification
<template> <div> <h3>Login verification</h3> <el-card class="login-card"> <!-- login form start --> <el-form ref="loginForm" :model="user" :rules="rules" label-width="80px"> <el-form-item label="user name" prop="username"> <el-input v-model="user.username" prefix-icon="el-icon-user" placeholder="enter one user name" clearable></el-input> </el-form-item> <el-form-item label="password" prop="password"> <el-input v-model="user.password" prefix-icon="el-icon-lock" placeholder="Please input a password" show-password clearable></el-input> </el-form-item> <el-form-item label="Confirm password" prop="repassword"> <el-input v-model="user.repassword" prefix-icon="el-icon-lock" placeholder="Please enter the password again" show-password clearable></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="login()">Sign in</el-button> <el-button type="info">Reset</el-button> </el-form-item> </el-form> <!-- login form end --> </el-card> </div> </template> <script> export default { data() { //Verification: the password is consistent with the confirmation password var validatePass2 = (rule, value, callback) => { if (value !== this.user.password) { callback(new Error('The two passwords are inconsistent!')); } else { callback(); } }; return { user: { username: '', password: '', repassword: '' }, rules: { username: [ { required: true, message: 'enter one user name', trigger: 'blur' }, { min: 3, max: 5, message: 'The user name is between 3 and 5 characters long', trigger: 'blur' } ], password: [ { required: true, message: 'Please input a password', trigger: 'blur' }, { min: 3, max: 5, message: 'The password is between 3 and 5 characters long', trigger: 'blur' } ], repassword: [ { required: true, message: 'Please enter the password again', trigger: 'blur' }, { validator: validatePass2, trigger: 'blur' } ] } } }, methods: { login() { // js object can be called in two ways: this user. Username or this user['username'] this.$refs.loginForm.validate((valid) => { if (valid) { // Verification passed alert('submit!'); } else { // Verification failed console.log('error submit!!'); return false; } }); } }, } </script> <style> .login-card{ width: 480px; } </style>
7. Common components
Button button
<template> <div> <el-button>Default button</el-button> <el-button type="primary">Main button</el-button> <el-button type="success">Success button</el-button> <el-button type="info">Information button</el-button> <el-button type="warning">Warning button</el-button> <el-button type="danger">Danger button</el-button> </div> </template> <script> export default { } </script> <style> </style>
Message prompt message
this.$message.success('This is a success message') this.$message.error('This is an error message')
<template> <div> <el-button type="info" @click="open1">news</el-button> <el-button type="success" @click="open2">success</el-button> <el-button type="warning" @click="open3">warning</el-button> <el-button type="danger" @click="open4">error</el-button> </div> </template> <script> export default { methods: { open1() { this.$message.info('This is a prompt message') }, open2() { this.$message.success('This is a success message') }, open3() { this.$message.warning('This is a warning message') }, open4() { this.$message.error('This is an error message') }, }, } </script> <style> </style>
Pop up messageboxconfirmation message
this.$confirm('This is a reminder','This is the title',{confirmButtonText: 'OK button',cancelButtonText: 'Cancel button',type: 'warning'}) .then(()=>{ // OK button callback this.$message.success('Deleted') // ajax operation }) .catch(()=>{ // Cancel button callback this.$message.error('Cancelled') })
Popup
Write pop-up layer
<template> <div> <el-button type="text" @click="dialogVisible = true">Click Open Dialog</el-button> <!-- Popup --> <el-dialog title="This is the title" :visible.sync="dialogVisible" > I am a text message <!-- Operation button --> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">Cancel</el-button> <el-button type="primary" @click="dialogVisible = false">determine</el-button> </span> </el-dialog> </div> </template> <script> export default { data() { return { dialogVisible: false, //Show pop-up layer } }, } </script> <style> </style>
drawer
<template> <div> <el-button type="primary" @click="drawerFormVisible = true">Modify student</el-button> <!-- drawer start --> <el-drawer title="I'm the title" :visible.sync="drawerFormVisible" direction="rtl" :before-close="handleClose"> <el-form :model="student" label-width="80px"> <el-form-item label="full name" > <el-input v-model="student.sname" autocomplete="off"></el-input> </el-form-item> <el-form-item label="class" > <el-select v-model="student.cid" placeholder="Please select a class"> <el-option label="Java12 class" value="c001"></el-option> <el-option label="Java34 class" value="c002"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="drawerFormVisible=false">determine</el-button> <el-button>cancel</el-button> </el-form-item> </el-form> </el-drawer> <!-- drawer end --> </div> </template> <script> export default { data() { return { drawerFormVisible: false, student: { } } }, methods: { handleClose(done) { this.$confirm('Confirm closing?') .then(_ => { //OK button done(); //End callback }) .catch(_ => { //cancel }); } }, } </script> <style> </style>
Tab
<template> <div> <el-tabs v-model="activeName" > <el-tab-pane label="user management " name="first"> user management <el-button type="primary" @click="activeName = 'second'">next step</el-button> </el-tab-pane> <el-tab-pane label="configuration management" name="second"> configuration management <el-button type="primary" @click="activeName = 'third'">next step</el-button> </el-tab-pane> <el-tab-pane label="Role management" name="third"> Role management <el-button type="primary" @click="activeName = 'fourth'">next step</el-button> </el-tab-pane> <el-tab-pane label="Timing task compensation" name="fourth"> Timing task compensation <el-button type="primary" @click="$message.success('succeed')">complete</el-button> </el-tab-pane> </el-tabs> </div> </template> <script> export default { data() { return { activeName: 'first' }; } } </script> <style> </style>
8.Tree component
Table structure
# Classification table CREATE TABLE t_category( tid VARCHAR(32) PRIMARY KEY COMMENT 'classification ID', tname VARCHAR(50) COMMENT 'Classification name', `status` INT DEFAULT '1' COMMENT 'Classification status: 0 disabled, 1 enabled', parent_id VARCHAR(32) COMMENT 'Parent classification ID', priority INT COMMENT 'The lower the priority, the higher the level of display', depth INT COMMENT 'Depth, increasing from 1' ); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1000','men's wear/Outdoor sports', NULL ,1,1); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2000','mobile phone/Digital', NULL ,2,1); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3000','snacks/fresh ', NULL ,3,1); #'t1000 ',' menswear / outdoor sports' INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1100','jacket', 't1000' ,1,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1200','trousers', 't1000' ,2,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1300','Popular trend', 't1000' ,3,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1110','Down Jackets', 't1100' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1120','cotton-padded clothes', 't1100' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1130','Sweater', 't1100' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1210','Leisure trousers', 't1200' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1220','Denim trousers', 't1200' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1230','sweatpants ', 't1200' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1310','Paratrooper pants', 't1300' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1320','Night running pants', 't1300' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t1330','Ice feeling T Shirt', 't1300' ,3,3); # 't2000 ',' mobile / digital ' INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2100','mobile phone', 't2000' ,1,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2200','Mobile Accessories', 't2000' ,2,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2300','Digital accessories', 't2000' ,3,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2110','Huawei Mobile', 't2100' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2120','iPhone', 't2100' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2130','vivo mobile phone', 't2100' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2210','Mobile phone shell', 't2200' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2220','Mobile phone earphone', 't2200' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2230','Mobile phone bracket', 't2200' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2310','U disc', 't2300' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2320','Hard disk', 't2300' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t2330','Battery', 't2300' ,3,3); # t2000 ',' snacks / fresh INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3100','Convenient fast food', 't3000' ,1,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3200','snacks', 't3000' ,2,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3300','well-known wine', 't3000' ,3,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3400','Milk ice', 't3000' ,4,2); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3110','instant noodles', 't3100' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3120','Ham sausage', 't3100' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3130','Canned dessert', 't3100' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3140','Pancake cold noodles', 't3100' ,4,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3210','Potato chips', 't3200' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3220','biscuit', 't3200' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3230','Internet celebrity IP', 't3200' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3240','Seafood', 't3200' ,4,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3310','Refreshing beer', 't3300' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3320','Slightly drunk red wine', 't3300' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3330','Health preserving yellow rice wine', 't3300' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3340','Famous Baijiu', 't3300' ,4,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3410','Yogurt', 't3400' ,1,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3420','Pure milk', 't3400' ,2,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3430','Powdered Milk', 't3400' ,3,3); INSERT INTO t_category(tid,tname,parent_id,priority,depth) VALUES('t3440','cheese', 't3400' ,4,3);
Backend implementation
JavaBean
package com.czxy.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @SuppressWarnings("serial") @TableName("t_category") @Data public class TCategory extends Model<TCategory> { //Category ID @TableId private String tid; //Classification name private String tname; //Classification status: 0 disabled, 1 enabled private Integer status; //Parent category ID private String parentId; //The lower the priority, the higher the level of display private Integer priority; //Depth, increasing from 1 private Integer depth; @TableField(exist = false) private List<TCategory> children = new ArrayList<>(); }
Controller
package com.czxy.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.api.ApiController; import com.baomidou.mybatisplus.extension.api.R; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.czxy.entity.TCategory; import com.czxy.service.TCategoryService; import com.czxy.vo.BaseResult; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("tCategory") public class TCategoryController extends ApiController { /** * service object */ @Resource private TCategoryService tCategoryService; @GetMapping public BaseResult<List<TCategory>> findAll() { // 1. Query all and click parent_id sort QueryWrapper<TCategory> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByAsc("parent_id"); List<TCategory> list = tCategoryService.list(queryWrapper); // 2. Handling data parent-child relationship List<TCategory> resultList = new ArrayList<>(); Map<String,TCategory> cacheMap = new HashMap<>(); list.forEach( tCategory -> { // 3.1 get parent classification TCategory parentCategory = cacheMap.get(tCategory.getParentId()); // 3.2 if no parent is added to the resultList, if there is a parent, add the internal parent if(parentCategory == null) { resultList.add(tCategory); } else { parentCategory.getChildren().add(tCategory); } // 3.3 cache itself cacheMap.put(tCategory.getTid() , tCategory); }); return BaseResult.ok("query was successful",resultList); } }
Front end basic implementation
<template> <div> <el-tree :data="categoryList" :props="defaultProps" show-checkbox @check-change="handleCheckChange"> </el-tree> </div> </template> <script> export default { data() { return { categoryList: [], defaultProps: { children: 'children', label: 'tname', disabled: (data,node) => { return data.status == 0 } } } }, methods: { async findAllCategory() { let { data } = await this.$http.get('http://localhost:7777/tCategory') this.categoryList = data.data }, handleCheckChange( data, checked, indeterminate ) { console.log(data, checked, indeterminate); } }, mounted() { this.findAllCategory() }, } </script> <style> </style>
modify state
Backend implementation
@PutMapping("/change") public BaseResult changeStatue(@RequestBody TCategory tCategory) { try { //1 query TCategory findCategory = tCategoryService.getById(tCategory.getTid()); Integer currentStatus = findCategory.getStatus(); //2. Status to be modified Integer status = currentStatus == 1 ? 0 : 1; //3.1 modify current Queue<TCategory> queue = new LinkedList<>(); queue.add(findCategory); //3.2 traversing the queue while(!queue.isEmpty()) { // 1) Win team leader TCategory currentCategory = queue.poll(); // 2) Modification status currentCategory.setStatus(status); tCategoryService.updateById(currentCategory); // 3) Get all child nodes QueryWrapper<TCategory> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("parent_id", currentCategory.getTid()); List<TCategory> list = tCategoryService.list(queryWrapper); queue.addAll(list); } //4 success return BaseResult.ok("Modified successfully"); } catch (Exception e) { e.printStackTrace(); return BaseResult.error(e.getMessage()); } }
Front end implementation
<template> <div> <el-tree :data="categoryList" :props="defaultProps" show-checkbox :expand-on-click-node="false" node-key="tid" :default-expanded-keys="expandedArr" @check-change="handleCheckChange"> <span class="custom-tree-node" slot-scope="{ node, data }"> <span>{{ node.label }}</span> <span> <el-button type="info" circle v-if="data.status == 1" size="mini" @click="() => changeCategoryStatus(data)">Disable</el-button> <el-button type="success" circle v-if="data.status == 0" size="mini" @click="() => changeCategoryStatus(data)">Enable</el-button> </span> </span> </el-tree> </div> </template> <script> export default { data() { return { categoryList: [], defaultProps: { id: 'tid', children: 'children', label: 'tname', disabled: (data,node) => { return data.status == 0 } }, expandedArr: [] } }, methods: { async findAllCategory() { let { data } = await this.$http.get('http://localhost:7777/tCategory') this.categoryList = data.data }, handleCheckChange( data, checked, indeterminate ) { console.log(data, checked, indeterminate); }, async changeCategoryStatus( nodeData ) { let { data } = await this.$http.put(`http://localhost:7777/tCategory/change`, nodeData) if(data.code == 1){ this.$message.success(data.message) this.findAllCategory() //Set expanded content this.expandedArr = [] this.expandedArr.push(nodeData.tid) } else { this.$message.error(data.message) } } }, mounted() { this.findAllCategory() }, } </script> <style> .custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; } </style>
9. Comprehensive cases
Pop up layer echo student information
Comprehensive case: click the student "modify" button to display the pop-up layer
Write form in pop-up layer
Write modification function
<template> <div> <!-- list --> <el-table :data="studentList" stripe border @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column prop="sid" label="number" width="150"></el-table-column> <el-table-column prop="sname" label="full name" width="150"></el-table-column> <el-table-column prop="gender" label="Gender" width="150"></el-table-column> <el-table-column prop="age" label="Age" width="150"></el-table-column> <el-table-column label="hobby" > <template slot-scope="scope"> <el-tag type="warning" v-for="(hobby,index) in scope.row.hobbies" :key="index">{{hobby}}</el-tag> </template> </el-table-column> <el-table-column label="operation"> <template slot-scope="scope"> <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">edit</el-button> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">delete</el-button> </template> </el-table-column> </el-table> <!-- Popup --> <el-dialog title="Modify student" :visible.sync="dialogFormVisible"> <el-form :model="student"> <el-form-item label="full name" label-width="80px"> <el-input v-model="student.sname" ></el-input> </el-form-item> <el-form-item label="Gender" label-width="80px"> <el-radio-group v-model="student.gender"> <el-radio label="male">schoolboy</el-radio> <el-radio label="female">girl student</el-radio> </el-radio-group> </el-form-item> <el-form-item label="Age" label-width="80px"> <el-input v-model="student.age" ></el-input> </el-form-item> <el-form-item label="hobby" label-width="80px"> <el-checkbox-group v-model="student.hobbies"> <el-checkbox label="smoking" name="type"></el-checkbox> <el-checkbox label="drink" name="type"></el-checkbox> <el-checkbox label="Hot head" name="type"></el-checkbox> </el-checkbox-group> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogFormVisible = false">Cancel</el-button> <el-button type="primary" @click="dialogFormVisible = false">determine</el-button> </div> </el-dialog> </div> </template> <script> export default { methods: { handleSelectionChange(val) { this.multipleSelection = val; //Save selected data }, handleEdit(index, row) { // Echo form this.student = row // Show pop-up layer this.dialogFormVisible = true }, handleDelete(index, row) { console.log(index, row); } }, data () { return { dialogFormVisible: false, // Whether the form pop-up layer is displayed multipleSelection: [], //Multiple selection, selected data studentList: [ { sid: 's001', sname: 'Zhang San', gender: 'male', age: 18, hobbies: ['smoking','drink','Hot head'] }, { sid: 's002', sname: 'Li Si', gender: 'female', age: 21, hobbies: ['smoking','Hot head'] } ], student: { } } } } </script> <style> .el-tag + .el-tag { margin-left: 10px; } </style>
10. Rotation chart
Rotation chart
<template> <div> <el-carousel :interval="4000" type="card" height="300px"> <el-carousel-item v-for="item in 6" :key="item"> <img src="@/assets/logo.png" alt=""> </el-carousel-item> </el-carousel> </div> </template> <script> export default { } </script> <style> .el-carousel__item img { width: 100%; height: 100%; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } </style>
Switch multiple pictures
<template> <div> <el-carousel :interval="1000" type="card" height="400px"> <el-carousel-item v-for="item in 3" :key="item"> <!-- <img src="@/assets/logo.png" alt="I'm a reminder"> --> <!-- <img src="@/assets/img/1.jpg" alt="I'm a reminder"> --> <img :src="require(`@/assets/img/${item}.jpg`)" alt="I'm a reminder"> </el-carousel-item> </el-carousel> </div> </template> <script> export default { } </script> <style> .el-carousel__item img { width: 100%; height: 100%; } /* Even background color */ .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } /* Odd background color */ .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } </style>
Complex drop-down list
Complete code
<template> <div> <el-form ref="form" :model="classes" label-width="80px"> <el-form-item label="Choose a teacher"> <el-select v-model="classes.teacherIds" @change="changeTeacher" multiple placeholder="Please select a teacher"> <el-option v-for="(teacher,index) in teacherList" :key="index" :label="teacher.tname" :value="teacher.id" :disabled="teacher.disabled" > <span style="float: left">{{ teacher.tname }}</span> <span style="float: right;">{{ teacher.typeText }}</span> </el-option> </el-select> </el-form-item> </el-form> {{classes}} </div> </template> <script> export default { data() { return { classes: { teacherIds: [] }, teacherList: [ { id: 't001', tname: 'Miss Liang Tong', type: '1', typeText: 'Instructor', disabled: false }, { id: 't002', tname: 'Mr. Ma Kun', type: '2', typeText: 'Assistant teacher', disabled: false }, { id: 't003', tname: 'Miss Zhong Yan', type: '3', typeText: 'Counselor teacher', disabled: false }, { id: 't004', tname: 'Miss Han Xiaojiao', type: '1', typeText: 'Instructor', disabled: false }, { id: 't005', tname: 'Mr. Dong Hongchao', type: '2', typeText: 'Assistant teacher', disabled: false }, { id: 't006', tname: 'Mr. Han Xinyuan', type: '3', typeText: 'Counselor teacher', disabled: false }, ] } }, methods: { changeTeacher(selectIds) { // Selected teacher id // 1 get the type corresponding to the selected teacher let selectType = this.teacherList.map(teacher => { if(selectIds.includes(teacher.id)) { return teacher.type } }); // 2. Data processing: other teachers of the same type but not the selected teacher are disabled this.teacherList.forEach(teacher => { if(selectType.includes(teacher.type) && !selectIds.includes(teacher.id)) { // Disable teacher.disabled = true } else { // Enable teacher.disabled = false } }) } }, } </script> <style> </style>