E-commerce project 01

###1. Overview of e-commerce business
Business services used by customers: PC end, applet, mobile web,
business services used by mobile app administrators: PC background management end.
The functions of the PC back-end management terminal: manage user accounts (login, logout, user management, authority management), commodity management (commodity classification, classification parameters, commodity information, orders), data statistics 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)

###2. Project initialization
A. Install Vue scaffolding
B. Create a project through scaffolding
C. Configure routing
D. Configure Element-UI: Install in plugins, search for vue-cli-plugin-element
E. Configure Axios: in dependencies Install, search for axios (running dependency)
F. Initialize the git warehouse
G. Host the local project to github or code cloud

###3. Code cloud related operations
A. Register for a login code cloud account
Insert picture description here

B. Install git
To use Git on Windows, you can download the installer directly from the official Git website to install it.
Test command: git --version

C. Click "Login" in the upper right corner of the website, log in to the code cloud, and set up your account
Insert picture description here

D. Create a public key locally: Run in the terminal: ssh-keygen -t rsa -C "[email protected]"
Insert picture description here

E. Find the public key address:
Your identification has been saved in /c/Users/My/.ssh/id_rsa.
Your public key has been saved in /c/Users/My/.ssh/id_rsa.pub.
When we create the public After the key is completed, please pay attention to the printed message "Your public key has been saved in"
/c/Users/My/.ssh/id_rsa.pub: id_rsa.pub under .ssh under Users under Users under C drive Is the public key we created

E. Open the id_rsa.pub file, copy all the codes in the file, click the SSH public key in the code cloud, and copy the generated public key to the public key
Insert picture description here
Insert picture description here

G. Test the public key: Open the terminal and enter the command
ssh -T [email protected]
Insert picture description here

H. Host the local code in Code Cloud
Click the + sign in the upper right corner of Code Cloud -> New Warehouse
Insert picture description here
Insert picture description here

I. Perform git configuration:

Insert picture description here

Open the terminal where the project is located and associate the git repository

Insert picture description here

###4. Configure the background project
A. Install phpStudy and import mysql database data
Insert picture description here

Insert picture description here

B. Install nodeJS, configure the background project, open the background project vue_api_server
from the terminal and enter the command in the terminal to install the project dependency package: npm install

C. Use postman to test the api interface
Insert picture description here

###5. Realize the login function
A. Keep the login status.
If the server and the client are of the same origin, it is recommended to use cookie or session to maintain the login status.
If the client and the server are cross-domain, it is recommended to use the token to maintain the login status.

B. Login logic:
Enter the account number and password on the login page to log in, and send the data to the server. The
server returns the result of the login. If the login is successful, the data will be returned with the token. The
client gets the token and saves it. Subsequent requests need to use this The token is sent to the server, and the server will verify the token to ensure the user's identity.

C. Add a new branch login and develop the current project vue_shop in the login branch:
open the vue_shop terminal and use git status to determine the current project status.
After confirming that the current working directory is clean, create a branch for development. After the development is completed, merge it into the master
git checkout -b login
and check the newly created branch: git branch
confirms that we are using the login branch for development
Insert picture description here

Then execute the vue ui command to open the ui interface, then run serve, run the app to view the current project effect
Insert picture description here

Found that it is now a default page, we need to change it, open the src directory of the project, and click the main.js file (entry file)

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './plugins/element.js'

Vue.config.productionTip = false


new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

Then open App.vue (root component), and sort out the content of the root component (leave the root node in the template, leave the default export in the script, remove the component, and remove all styles in the style)

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
</style>

Then open router.js (route), clear the routing rules in the routes array, then delete the views and delete the helloworld.vue in the components

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    
  ]
})

Create a new Login.vue component in the components folder, add template, script, and style tags. The scoped in the style tag can prevent style conflicts between components. Without scoped, the style is global

<template>
    <div class="login_container">
        
    </div>
</template>

<script>
export default {
  
}
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b5b6b;
  height: 100%;
}

</style>

Import components and set rules
in router.js Add routing placeholders in App.vue

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login }
  ]
})

When we add styles to the content in Login.vue, it will report the error "Lack of less-loader", we need to configure the less loader (development dependency) and install less (development dependency)
Insert picture description here

Then you need to add a public style, add a css folder under the assets folder, create a global.css file, and add a global style

/* 全局样式表 */
html,body,#app{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0; 
}

Import
global.css in main.js to make the global style effective. import "./assets/css/global.css" and then the root element in Login.vue also needs to be set to fill the full screen (height: 100%) and
finally Login.vue The code in the file is as follows

<template>
    <div class="login_container">
        <!-- 登录盒子  -->
        <div class="login_box">
            <!-- 头像 -->
            <div class="avatar_box">
                <img src="../assets/logo.png" alt="">
            </div>
            <!-- 登录表单 -->
            <el-form :model="loginForm" ref="LoginFormRef" :rules="loginFormRules" label-width="0px" class="login_form">
                <!-- 用户名 -->
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" prefix-icon="iconfont icon-user" ></el-input>
                </el-form-item> 
                <!-- 密码 -->
                <el-form-item prop="password">
                    <el-input type="password" v-model="loginForm.password" prefix-icon="iconfont icon-3702mima"></el-input>
                </el-form-item> 
                <!-- 按钮 -->
                <el-form-item class="btns">
                    <el-button type="primary" @click="login">登录</el-button>
                    <el-button type="info" @click="resetLoginForm">重置</el-button>
                </el-form-item> 
            </el-form>
        </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      //数据绑定
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      //表单验证规则
      loginFormRules: {
        username: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '登录名长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  //添加行为,
  methods: {
    //添加表单重置方法
    resetLoginForm() {
      //this=>当前组件对象,其中的属性$refs包含了设置的表单ref
      //   console.log(this)
      this.$refs.LoginFormRef.resetFields()
    },
    login() {
      //点击登录的时候先调用validate方法验证表单内容是否有误
      this.$refs.LoginFormRef.validate(async valid => {
        console.log(this.loginFormRules)
        //如果valid参数为true则验证通过
        if (!valid) {
          return
        }

        //发送请求进行登录
        const { data: res } = await this.$http.post('login', this.loginForm)
        //   console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error('登录失败:' + res.meta.msg) //console.log("登录失败:"+res.meta.msg)
        }

        this.$message.success('登录成功')
        console.log(res)
        //保存token
        window.sessionStorage.setItem('token', res.data.token)
        // 导航至/home
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b5b6b;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 300px;
  background: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  .avatar_box {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}
.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
.btns {
  display: flex;
  justify-content: flex-end;
}
</style>

Among them, we have some useful content and need to be further processed:

A. Add the form component of element-ui
Open the element.js file in the plugins folder to
import elementui on-demand import Vue from'vue '
import {Button} from'element -ui'
import {Form, FormItem} from ' element-ui'
import {Input} from'element-ui'

Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)

B. add third-party font
fonts file folder to copy creative assets, by introducing import './assets/fonts/iconfont.css' main.js file in the inlet
was then directly
followed by the addition login box

C. Steps to add form validation
1). Add attributes: rules="rules", rules are a bunch of validation rules, defined in script,
2). Add rules in script: export default{ data(){return{ …, rules: { name: [ {required: true, message:'Please enter the activity name', trigger:'blur' }, {min: 3, max: 5, message:'Length is 3 to 5 characters', trigger:'blur'} ], region: [ {required: true, message:'Please select the active region', trigger:'change'} ] }… 3). Set the validation rules through the prop property








4. Import axios to send ajax requests.
Open main.js, import axios from'axios';
set the root path of the request: axios.defaults.baseURL ='http://127.0.0.1:8888/api/private/v1/' ;
Mount axios: Vue.prototype.$http = axios;

5. Configure the pop-up prompt:
open the element.js file in the plugins folder, and
import elementui on-demand import {Message}
from'element -ui' for global mounting: Vue.prototype. message = M essage; in login . Write the pop-up code in the vue component: this. message = Message; Write the pop-up code in the login.vue component: this.message=Message;In L O G I n- . V U E group members in knitting write projectile window Generation Code : T H I S . Message.Error An ( "Login Failed")

###6. Operations
after successful login A. After successful login, you need to save the token returned from the background to sessionStorage.
After the operation is completed, you need to jump to /home

login() {
      //点击登录的时候先调用validate方法验证表单内容是否有误
      this.$refs.LoginFormRef.validate(async valid => {
        console.log(this.loginFormRules)
        //如果valid参数为true则验证通过
        if (!valid) {
          return
        }

        //发送请求进行登录
        const { data: res } = await this.$http.post('login', this.loginForm)
        //   console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error('登录失败:' + res.meta.msg) //console.log("登录失败:"+res.meta.msg)
        }

        this.$message.success('登录成功')
        console.log(res)
        //保存token
        window.sessionStorage.setItem('token', res.data.token)
        // 导航至/home
        this.$router.push('/home')
      })
    }

Add a component Home.vue, and add rules for it

<template>
    <div>
        this is home
        <el-button type="info" @click="logout"> 退出 </el-button>
    </div>
</template>

<script>
export default {
  methods: {
    logout() {
      window.sessionStorage.clear()
      this.$router.push('/login')
    }
  }
}
</script>

<style lang='less' scoped>
</style>

Add routing rules

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    { path: '/home', component: Home }
  ]
})

Add a router guard
If the user is not logged in and cannot access /home, if the user accesses directly through the url address, it will be forced to jump to the login page.
Open router.js

import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login.vue'
import Home from './components/Home.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    { path:'/', redirect:'/login'},
    { path:'/login' , component:Login },
    { path:'/home' , component:Home}
  ]
})

//挂载路由导航守卫,to表示将要访问的路径,from表示从哪里来,next是下一个要做的操作
router.beforeEach((to,from,next)=>{ 
  if(to.path === '/login')
    return next();
  
  //获取token
  const tokenStr = window.sessionStorage.getItem('token');

  if(!tokenStr)
    return next('/login');

  next();

})

export default router 

Realize the exit function
Add an exit function button to the Home component, add a click event to the exit button, and add event handling code as follows:

export default {
    methods:{
        logout(){
            window.sessionStorage.clear();
            this.$router.push('/login');
        }
    }
}

###Supplement
A. Handling ESLint warnings
Open the scaffolding panel and view the warning message
[Picture]
By default, ESLint and vscode formatting tools conflict, and you need to add a configuration file to resolve the conflict.
Add the .prettierrc file in the project root directory

{
    "semi":false,
    "singleQuote":true
}

Open the .eslintrc.js file and disable the space-before-function-paren check:

  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'space-before-function-paren' : 0
  },

B. Merge element-ui imported on demand

import Vue from 'vue'
import { Button, Form, FormItem, Input, Message } from 'element-ui'

Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
// 进行全局挂载:
Vue.prototype.$message = Message

C. Submit the code to Code Cloud
Create a new project terminal, enter the command'git status' to view the modified and new file content.
Add all files to the temporary storage area: git add.
Submit all the code to the local warehouse: git commit -m "Add the login function and the basic structure of /home" to
view the branch: git branch found that all the code has been submitted to the login branch.
Merge the login branch code to the master branch, first switch to the master: git checkout master is
performed in the master branch Code merge: git merge login
pushes the local master to the remote code cloud: git push

Push the local sub-branch to the code cloud, first switch to the sub branch: git checkout branch name
and then push to the code cloud: git push -u origin remote branch name

Guess you like

Origin blog.csdn.net/weixin_48116269/article/details/109126103