E-commerce
E-commerce
Business description
Multi-end
Business services used by customers: PC, applet, mobile web, mobile app
E-commerce background
Business services used by administrators: PC background management terminal
PC background management terminal functions: manage user accounts (login, logout, user management, authority management), commodity management (commodity classification, classification
parameters, commodity information, orders), data statistics
Development model
The e-commerce back-end management system adopts a development model of separation of front and back ends
- The front-end project is a Vue-based SPA (Single Page Application) project
- Front-end technology stack: Vue, Vue-Router, Element-UI, Axios, Echarts
- Back-end technology stack: Node.js, Express, Jwt (simulation session), Mysql, Sequelize (framework for operating databases)
Start the background project
Enter the vue-api-server directory and run the following command to resume installation
npm install
Create a new database shop_admin, find shop_admin.sql in the db directory, and import the data.
View the default.json in the config directory, and modify the database configuration information to be consistent with your database.
Run the following command to start the background project
node app.js
Test
http://127.0.0.1:8888/api/private/v1/goods
Project initialization
Proceed as follows
1. Code Cloud to create a warehouse
2. Create a project locally
vue create vue-shop
3. Use git to push the project to the remote warehouse
command | Description |
---|---|
mkdir shop-view | Create a file |
cd shop-vue | open a file |
git init | initialization |
touch README . md | New README |
git add README . md | Submit to staging area |
git commit -m “first commit” | Submit changes |
git remote add origin git@gitee . com: dqtc/shop-vue. git | Remote warehouse |
git push -u origin master | Push to remote |
Note: The remote warehouse is different from the other, don’t copy casually
4. Placement Element-UI
installation
npm i element-ui -S
-S means --save
Project introduction
Complete introduction
Write the following in main.js:
import : Vue from ,' vue
import App from ,' . /App.vue
import : router : from ' . /router
import- store from : ' ./store
import。ElementUI from . ' element-ui
import ' element-ui/lib/ theme -chalk/ index . css '
Vue . use(ElementUI )
Vue . config . productionTip = false
new. Vue({
router,
store,
render: h => h(App)
}) . $mount( #app' )
On-demand introduction:
With the help of babel-plugin-component, we can introduce only the components we need to achieve the purpose of reducing the size of the project.
First, install babel-plugin-component:
npm install babel-plugin-component -D
Then, modify .babelrc to:
{
"presets": [["es2015", { "modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
Next, if you only want to introduce some components, such as Button and Select, you need to write the following in main.js:
import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
/* 或写为
* Vue.use(Button)
* Vue.use(Select)
*/
new Vue({
el: '#app',
render: h => h(App)
});
5. Configure axios
$ npm install axios
Also want to know the relevant knowledge points , please click
6 Delete components and views
There are some built-in sample components in vue that can be deleted, for example:
delete Home.vue and About.vue in the views directory under the src directory,
delete HelloWorld.vue in the components directory
7. Code format verification
Because ESLint is installed, the code will be checked according to the eslint specification when saving the code, such as semicolons, double quotes, spaces, etc.
If you are not careful, you will not be able to pass the verification, resulting in packaging failure
solution
Install ESLint extension
{
// vscode默认启用了根据文件类型自动设置tabsize的选项
"editor.detectIndentation": false,
// 重新设定tabsize
"editor.tabSize": 2,
// #每次保存的时候自动格式化
"editor.formatOnSave": true,
// #每次保存的时候将代码按eslint格式进行修复
// 添加 vue 支持
"eslint.validate": [
"javascript",
"javascriptreact",
"vue"
],
// #让函数(名)和后面的括号之间加个空格 不加空格false
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
// #让vue中的js按编辑器自带的ts格式进行格式化
"vetur.format.defaultFormatter.js": "vscode-typescript",
"vetur.format.defaultFormatterOptions": {
"js-beautify-html": {
"wrap_attributes": "force-aligned"
// #vue组件中html代码格式化样式
}
},
"window.zoomLevel": 0,
"explorer.confirmDelete": false,
"explorer.confirmDragAndDrop": false,
"editor.renderControlCharacters": true,
"editor.renderWhitespace": "all",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.fontSize": 18
}
log in
1. Login logic
Enter the account and password on the login page to log in, and send the data to the server
The server returns the login result
Return data if login is successful
数据中带有token,客户端得到token并进行保存,后续的请求都需要将此token送给服务器,服务器会验证token以保证用户身份
If login fails, an error message will be displayed on the front end
2. Create a new branch login
Develop the current project in the login branch
Open the terminal in vs code, use git status to determine the current project status, and after
confirming that the current working directory is clean, create a branch for development,
and then view the newly created branch:
git branch
Merge it into master after development
git checkout -b login
Note: When writing, make sure whether it is under the login branch
3. Modify the root component
Modify App.vue (root component), leaving only the routing exit
<template>
<div id="app">
<router-view />
</div>
</template>
<style>
* {
margin: 0;
padding: 0;
}
html,
body,
#app {
height: 100%;
}
</style>
4. Create a login component
Create a new Login folder in the views folder, and create new index.vue and imgs folders in the Login folder
index.vue template
<template>
<div class="login-container">
<div class="login-box">
<!-- 网站logo -->
<div class="logo-box">
<img src="./imgs/login.jpg" alt />
</div>
<!-- 表单 -->
<el-form ref="form" :model="loginForm" class="loginForm">
<el-form-item>
<el-input v-model="loginForm.username" placeholder="输入用户名" prefix-
icon="el-icon-user-solid"></el-input>
</el-form-item>
<el-form-item>
<el-input v-model="loginForm.password" placeholder="输入密码" prefix-
icon="el-icon-view"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary">登录</el-button>
<el-button type="info">重置</el-button>
</el-form-item>
</el-form>
</div>
</div>
</template>
- The login image is dedicated to the login component, and other components are basically not used, so put it in the Login/imgs directory instead of the assets directory
- The form components in element-ui are used here. If the element-ui is introduced on-demand, you need to pay attention to the introduction of the corresponding components. If it is a complete introduction, you can ignore this one
- Each form is composed of a form-item, which can prevent various types of form controls, including Input, Select, Checkbox, Radio, Switch, DatePicker, TimePicker
- The form can use the model attribute to specify a form data object, which needs to be provided in data
Style and install less-loader
<style lang="less" scoped>
.login-container {
background-color: #303133;
height: 100%;
.login-box {
width: 450px;
height: 310px;
background-color: #fff;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 5px;
.logo-box {
position: absolute;
width: 150px;
height: 150px;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
background: #fff;
padding: 5px;
box-shadow: 0 0 10px #eee;
img {
width: 100%;
height: 100%;
border-radius: 50%;
}
}
.loginForm {
position: absolute;
top: 120px;
width: 100%;
padding: 0 20px;
box-sizing: border-box;
text-align: center;
}
}
}
</style>
The less syntax is used above, so less and less-loader need to be installed
npm install less less-loader -D
Sometimes an error will be reported because of version issues
Solution for error report due to version issue:
Solution 1: Uninstall the higher version and install the lower version
Need to uninstall the current version of less-loader
npm uninstall less-loader
Install a suitable version, such as: 7.3.0
npm i less-loader
Solution 2: When creating a vue project, choose less
Global style
It is best to create a new css directory in the assets, and create a new common.css under the css directory to
write global styles in it
* {
margin: 0;
padding: 0;
}
html,
body,
#app {
height: 100%;
}
Then import it in main.js
import './assets/css/common.css'
Of course, it can also be set directly in App.vue, so that all components displayed through the routing exit in App.vue will use this style, but components that are not displayed through the routing exit will not be used. In addition, if there are too many styles, It’s messy, so it’s better not to use this method
Add route
Add routing rules in router/index.js
Add third-party fonts
You can go to iconfont to find and download it locally. After decompression, rename it to font, then copy it to the assets directory, and import iconfont.css into main.js
import './assets/fonts/iconfont.css'
And then use it in the component
Another method is to generate a link and directly introduce
<link rel="stylesheet" href="//at.alicdn.com/t/font_2420827_3nyqzotc4zn.css">
to sum up
- Method 1 will package iconfont.css into the program, the final project file will be larger, but no additional request is required
- Method 2 does not need to be packaged, so the project size will be smaller, but an additional request is added, but the request is for Ali's server, so it will not cause pressure on our own server
Add form validation
给添加属性:rules="formLoginRules",formLoginRules是一堆验证规则,定义在script中
在data中定义formLoginRules规则的具体内容
export default {
data() {
return {
loginForm: {
username: "",
password: ""
},
// 定义验证规则列表
loginFormRules: {
username: [
{ required: true, message: "请输入用户名", trigger: "blur" },
{ min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
],
password: [
{ required: true, message: "请输入密码", trigger: "blur" },
{ min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" }
]
}
};
methods: {
submitForm (form) {
this.$refs.form.validate(valide => {
console.log(valide)
if (valide) {
console.log('发送 ajax 请求')
} else {
console.log('不发送')
}
})
}
}
}
};
Set the validation rules through the prop attribute
<el-form-item label="活动名称" prop="username">
Use axios
Add the following code to main.js
// 引入 axios
import axios from 'axios'
// 挂载到 Vue 原型上
Vue.prototype.$http = axios
Configure the root path of the request.
There are many back-end interfaces, and the interface base address: http://127.0.0.1:8888/api/private/v1/
Each request url writes this, which will cause the url address to be too long, and the interface will be changed later. inconvenient
Set the root path of axios request by the following code
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/';
Combining the above code, the final code becomes
// 引入 axios
import axios from 'axios'
// 设置请求根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
// 挂载到 Vue 原型上
Vue.prototype.$http = axios
Request login interface
submitForm (form) {
this.$refs.form.validate(valide => {
if (valide) {
// 请求登录
this.$http.post('login', this.loginForm)
.then(res => {
const { status, msg } = res.data.meta
if (status === 200) {
const { data: { token } } = res.data
localStorage.setItem('token', token)
} else if (status === 400) {
console.log(msg)
}
})
} else {
console.log('填入的表单数据不正确')
}
})
}
- After success, determine the status value, 200, indicating that the login is successful, 400 indicating that the requested address does not exist or contains unsupported parameters
- Local storage can use localstorage or sessionstorage
Asynchronous transformation
- The parameter of validate is the callback function
- Although the post method returns a promise, the then method of the promise is also a callback function
Modify login code
async submitForm (form) {
try {
// 进行表达校验
await this.$refs.form.validate()
const res = await this.$http.post('login', this.loginForm)
const { status, msg } = res.data.meta
if (status === 200) {
const { data: { token } } = res.data
localStorage.setItem('token', token)
} else if (status === 400) {
console.log(msg)
}
} catch (err) {
console.log('验证未通过')
}
}
Successful login jump
Create a Home directory under the views directory, and create a new index.vue under this directory
<template>
<div>
this is home
<el-button type="info" @click="logout"> 退出 </el-button>
</div>
</template>
<script>
export default {
methods: {
logout () {
window.localStorage.clear()
this.$router.push('/login')
}
}
}
</script>
<style lang='less' scoped>
</style>
Modify the login method submitForm, after successful login, add the following code
this.$router.push('home')
Add routing rules
const routes = [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/home',
name: 'Home',
component: Home
}
]