Vue3.0 Basic Learning Project-simple Background Management System

Vue3.0 project combat

Tutorial official website: http://www.web-jshtml.cn/#/Video address: https://www.bilibili.com/video/BV1zJ411g7Fx Official source code: vue-admin

Learning content : Vue+Vuex+Router+ElementUi+Webpack family bucket, VUE3.0 experience version API, component development, life cycle, routing permissions, Sass, Axios interceptor, cache, project deployment, Nginx, domain name, server, GIT , Prototype, interface joint debugging, performance, cache, etc.;

Vue learning : VUECLI scaffolding projects, ElementUI components, VUE instructions, Vuex, State, Getters, Mutations, components, props, propsData, computed, watch, cookie storage, sessionStorage storage, localStorage storage, routing guards, detection tokens, etc. ;

Learning results : Completely build a back-end management system independently, clarify the overall process of the system, master the company-level project development process (from prototype, UI, project development, back-end joint debugging, test engineer, BUG repair, project deployment, project iteration), VUE components Development of integrated thinking (one of the core), real business interface joint debugging, routing authority (role assignment, system assignment, button level authority), Nginx project deployment and forwarding, business logic extraction, API interface modularization, GIT code management (basic git command), module system add, delete, modify, check (information function, user function), Qiniu cloud third-party storage, HTML5 local storage;


1st class hour

1.1 Project development process

1.2 Business flowchart

1.3 Program flow chart

1.4 Test case

Lesson 2

2.1 Environmental installation

  1. Install node.js

https://nodejs.org/en/download/

Check the version number node -v, npm -v The installation is successful when the version number appears. (If it does not appear, please restart the computer and try again) node8.9 or above

  1. Manage nodejs version (optional)

Execute the command to install: npm install -gn

n latest (upgrade node.js to the latest version)

n stable (upgrade node.js to the latest stable version)

n can also be followed by the version number, for example: $ n v0.10.26 or $ n 0.10.26

  1. Install vue-cli3.0 scaffolding globally

Uninstallation: If you have installed the old version of vue-cli (1.x or 2.x) globally, you need to uninstall it first: npm uninstall vue-cli -g

Installation: npm install -g @vue/cli

Check the version number: vue -V, the installation is successful when the version number appears.

Bridge 3.0 to 2.0 version: npm install -g @vue/cli-init

2.2 Establish project warehouse

Note that you can use the git visual management tool GitKraken -Tutorial 9

2.3 Build the project

$ vue create vue-admin

Lesson 3

3.1 Vue-cli

3.2 vue.config.js

vue.config.jsIt is an optional configuration file, if the project (and package.jsonthe existence of this document at the same level) in the root directory, then it will be @vue/cli-serviceloaded automatically. You can also use package.jsonthe vuefield, but note that such an approach requires you to strictly comply with JSON format to write. It is different from the configuration in webpack.config.js in vue2.0-cli.

Vue.config.js // 
Module1 . Exports  =  { 
  // Configuration Options ... 
}

3.3 routing lazy loading

Route lazy loading means that the corresponding components are loaded when the route is accessed.

Traditional routing:

import Home from "../views/Home.vue";
Vue.use([
  {
    path:'/',
    name:'Home',
    component: Home 
  }
]);

Routing lazy loading writing:

Vue.use([
  {
    path:'/',
    name:'Home',
    component: ()=> import('../views/Home.vue')
  }
]);

3.4 route redirection

// Redirect from /a to /b 
const  router  =  new  VueRouter ( { 
  routes : [ 
    {  path : '/a' ,  redirect : '/b'  } 
  ] 
} ) 
// Redirect to the component named foo 
const  router  =  new  VueRouter ( { 
  routes : [ 
    {  path : '/a' ,  redirect : {  name : 'foo'  } } 
  ] 
} )

3.5 Element-UI

Official website: Element-UI

  1. Installation depends -npm i element-ui --S
  2. Global introduction
import ElementUI from 'element-ui'; 
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

Lesson 4

4.1 Vue file rules

4.2 Vue basic instructions

  • v-model : Create two-way binding on form controls or components.
  • v-bind binding attribute : binding method v-bind:attributeName or:attributeName
  • v-for : Render the element or template block multiple times based on the source data, and add it to the looped template instead of the parent element
<div v-for=“(item, index) in items“ :key=“item.id”> 
    {{ item.text }} 
</div> 
  • v-show / v-if
  • v-show: Add display to the element to hide the DOM element
  • v-if: directly delete DOM elements. When there is an interface in the DOM element, when the v-if value is true, the interface will be requested.

4.3: binding method of class

See the official documentation -Class binding and Style

  1. basic method
<div v-bind:class="{ active: isActive }"></div>
<script>
    export default {
        data() {
            return {
                isActive: true
            }
        }
    }
</script>
  1. expression
<div v-bind:class="{ active: isActive === -1 }"></div>
<script>
    export default {
        data() {
            return {
                isActive: 2
            }
        }
    }
</script>
  1. Multiple bindings
// method 1 
<div v-bind:class="{ active: isActive, sort: isSort }"></div>
 <script>
    export default {
        data() {
            return {
                isActive: true,
                isSort: false
            }
        }
    }
</script>

// Method 2
<div v-bind:class="classObject"></div>
<script>
    export default {
        data() {
            return {
                classObject: {active:true,sort:false}
            }
        }
    }
</script>
  1. Array binding-the array is a specific class name, and the above objects are judged by true/false
<div v-bind:class="[isActive, isSort]"></div>
<script>
    export default {
        data() {
            return {
                isActive: 'active',
                isSort: 'sort'
            }
        }
    }
</script>
  1. Multiple ways to combine
<div v-bind:class="[{active: isActive}, isSort, isNew ? newClass : '']"></div>
<script>
    export default {
        data() {
            return {
                isActive: true,
                isNew: false
            }
        }
    }
</script>

Lesson 5

5.1 Form validation rules

  • Verify email: let reg = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+.([a-zA-Z] {2,4})$/
  • Letters + numbers: let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/
  • Letters or numbers: left reg = /^[a-z0-9]{6}$/
  • Special character filtering
function strFilter(s){
  const pattern = new RegExp("[`~!@#$^&*()=|{}':;,.<>/?!¥…()—【】‘;:”“。,、?]");
  let re = '';
  for (let i = 0; i < s.length; i++) {
     rs = rs + s.substr(i, 1).replace(pattern, '');
  }
  return re;
}

6th class hour

Nothing.

Lesson 7

7.1 Composition API

Detailed Explanation of Composition API: https://vue-composition-api-rfc.netlify.com /

$npm install @vue/composition-api --save
// Main.js 
import  VueCompositionApi  from  '@ vue / composition-api' ; 
View . use ( VueCompositionApi ) ;

Vue3.0 new feature syntax

First need to introduce relevant

1. Setup function

According to the official statement, the setup function is a new Vue component option and the entry point for using the Composition API in the component.

export default {
  setup(props, context) {
    /* attrs: (...) == this.$attrs
      emit: (...) == this.$emit
      listeners: (...) == this.$listeners
      parent: (...) == this.$parent
      refs: (...) == this.$refs
      root: (...) == this */
    // ......
  }
}

Special attention should be paid to the 3.0 syntax, ElementUI etc. can no longer be used directly this.???. This should be replaced with root.

  1. Declaration object**

In Vue2.0, it is data(){ return {} }, while in Vue3.0, the use of recative() and ref()

  • Reactive (used when declaring a single object)
const  obj  =  reactive ( { count : 0 } ) 
// Get the value 
console . log ( obj . count )  // 0
  • ref (used when declaring basic data type variables)
const  number  =  ref ( 0 ) ; 
// Get the value 
. value console . log ( number . value )  // 0
  • isRef (check whether an object is a ref object)
const unwrapped = isRef(number) ? number.value : number;
  • toRefs (toRefs converts reactive objects into ordinary objects)

Ensure that the object deconstruction or expansion operator will not lose the response of the original reactive object

// Ordinary object 
const  obj  =  { a : 1 ,  b : 2 } 
let  { a , b }  =  obj 
console . Log ( a ,  b )  // 1 2 
// reactve object 
const  reactiveObj  =  reactive ( { a : 1 ,  b : 2 } ) 
let  { a , b }  =  newObj  // 1 2
const  newObj  =  toRefs ( reactiveObj ) 
let  { a , b }  =  newObj 
console . log ( a ,  b )  // RefImpl{} RefImpl{} 
newObj . a  // Cannot get 
newObj . a . value  // 1-Need to add value

Life cycle functions in Composition API

import { onMounted, onUpdated, onUnmounted } from 'vue'
const MyComponent = {
  setup() {
    onMounted(() => {
      console.log('mounted!')
    })
    onUpdated(() => {
      console.log('updated!')
    })
    onUnmounted(() => {
      console.log('unmounted!')
    })
  }
}

8th class hour

8.1 axios interceptor

Official website: axios installationnpm install axios

First of all, in order to avoid repeated writing of interfaces between components, it is necessary to separate the interfaces and form a separate api file to import.

Then define the interceptor and introduce the interceptor in the corresponding api for processing.

Examples of interceptor applications:

// add request interceptor 
axios . Interceptors . Request . Use ( function  ( config )  { 
    // what to do before sending the request 
    return  config ; 
  } ,  function  ( error )  { 
    // what to do on request error 
    return  Promise . Reject ( error ) ; 
  } ) ;

// Add response interceptor 
axios . Interceptors . Response . Use ( function  ( response )  { 
    // do something with response data 
    return  response ; 
  } ,  function  ( error )  { 
    // do something with response error 
    return  Promise . Reject ( error ) ; 
  } ) ;

Generally, some parameters are added to the request in the request interceptor: Tokey, userID…

8.2 Module Reference

Exporting through export default does not require {} to import, but only one function can be exported in this way;

// file1.js
function service(){}
export default service;
// file2.js
import service from 'file1.js'

Import needs {} when exporting through export, and multiple functions can be exported;

// file1.js
function service1(){}
function service2(){}
export {service1, service2};
// file2.js
import {service1, service2} from 'file1.js'

8.3 Interface documentation

For details, please see: http://www.web-jshtml.cn/file/api.html

9th class hour

9.1 Environment variables and modes

By default, a Vue CLI project has three modes:

  • development Pattern for development environment
  • production Mode for production environment (project goes online)
  • test Mode for testing

Pass process.env.NODE_ENVthe value development/production to know what environment it is in at this time, and we can make different configurations according to the current environment, for example:

publicPath : process . env . NODE_ENV  ===  'production' ? '' : '/' ,   // basic path 
outputDir : process . env . NODE_ENV  ===  'production' ? 'dist' : 'devdist' ,  // output File Directory

We can also be created in the project root directory named .env.developmentfile, then the variable is declared in this file will only be loaded in a development mode, production empathy.

Environment variables :

  • In VUE_APP_the beginning - provided, for example VUE_APP_SECRET=secret, the build process, process.env.VUE_APP_SECRETwill be secretreplaced.
  • NODE_ENV- would be "development""production"or "test"one of the.
  • BASE_URL- and will be vue.config.jsin the publicPathoptions match, that your application will be deployed to the base path.

9.2 Cross-domain settings

  1. The corresponding URL for the local http://192.168.1.106:8080call /getSmsinterface ishttp://192.168.1.106:8080/getSms/
  2. baseURL setting-equivalent to adding a prefix before the excuse to visit
  • If the baseURL of axios is set to http://192.168.1.1, the corresponding URL at this time ishttp://192.168.1.1/getSms/
const service = axios.create({
    baseURL: 'http://192.168.1.1',
    timeout: 1000, // 超时
})
  • If the baseURL of axios is set to /api, the corresponding URL at this time ishttp://192.168.1.106:8080/api/getSms/
const service = axios.create({
    baseURL: '/api',
    timeout: 1000, // 超时
})
  1. In vue.config.js cross-domain configuration - met / api, speaking in front of the domain name is converted to a target, that is, the original domain name when accessing http://192.168.1.106:8080/api/getSms/become http://www.web-jshtml.cn/productapi/api/getSms/, at this time we do not need /apithe aid of pathRewrite it goes empty, The final visit urk ishttp://www.web-jshtml.cn/productapi/getSms/
proxy: {  
    '/api' : { 
        target : 'http : //www.web-jshtml.cn/productapi ' ,  // service address 
        changeOrigin : true , 
        pathRewrite : { 
            '^/api' : '' 
        } 
    } 
}

Lesson 10

No

Lesson 11

11.1 setTimeout/setInterval

Requirements: The verification code button is disabled during the request process and displays “Sending”. After the request is successful, it displays “Resending” after the 60s countdown.

Through setTimeout/setInterval to achieve, but pay attention to, setTimeout/setInterval should be cleared during use! ! !

  • setTimeout:clearTimeout(variable) is executed only once
  • setInterval:clearInterval(variable) is executed continuously, it needs a condition to stop

Lesson 12

12.1 The promise object

Mainly understand four contents, resolve, reject, all, race.

  • Common grammar
let promise = new Promise((resolve, reject) => {
    // ...
})
promise.then(response => {
    console.log('成功')
    console.log(response)
}).catch(error => {
    console.log('失败')
    console.log(error)
})
  • All method-all promises in the array are resolved before executing then, as long as one of the returns (reject) is unsuccessful, catch is executed.
Promise . All ( [ promise1 ( true ) ,  promise2 ( true ) ,  promise3 ( true ) ] ) . Then ( response  =>  { 
    console . Log ( 'All calls succeeded' ) ; 
} ) . Catch ( error  =>  { 
    console . log ( 'Some may have failed' ) ; 
} )
  • Race method-racing, only one changes the state first, and the final state changes accordingly.
Promise.race([promise1(false), promise2(true), promise3(true)]).then(response => {
    console.log('成功');
}).catch(error => {
    console.log('失败了');
})

Lesson 13

13.1 Password sha1 encryption

After installing js-sha1, import sha1 from 'js-sha1'import it and use it directly sha1().

$npm install js-sha1

Password encryption process:

  1. Pre-encrypted once on the front end
  2. Login password: 123456 (normal string)
  3. After encryption: sha1(‘123456’) == ‘541216ad5s4f5ds1f5asd4f65asd4’ (encrypted string)
  4. Background encryption
  5. String received: ‘541216ad5s4f5ds1f5asd4f65asd4’
  6. Encrypt again in the background: md5(‘541216ad5s4f5ds1f5asd4f65asd4’) == ‘8f9qwersd3g165y4d1sf3s1f6aew4’ (the final encrypted password)
  7. Login-the user name is matched with the encrypted password, login is successful, or prompted if it fails

14th class hour

Nothing.

15th class hour

15.1 Router routing

  1. A jump in HTML tags to form - provided the template <router-link>can be
<!-- Jump without parameters --> 
< router-link : to = " {name : ' index ' } " > Jump link 1</ router-link >
< router-link : to = " {path : ' /index ' } " >Jump link 2</ router-link >
 <!-- Jump with parameters --> 
< router-link : to = " {name : ' index ' ,params : {id : 1 }} " >Jump link 3</ router-link >
<router-link :to="{name:'index',query:{id:1}}">跳转链接3</router-link>
  1. JS is set to jump in - call functions this.$router.push()can be
// Jump without parameters 
this . $router . Push ( '/home' ) ; 
this . $router . Push ( { name : 'home' } ) ; 
this . $router . Push ( { path : '/home' } ) ; 
// Jump with parameters 
this . $router . Push ( { name : 'home' , query : { id : '1'} } )  
this . $router . push ( { path : '/home' , query : { id : '1' } } )  // Parameter receiving: this.$route.query.xxxxxxx 
this . $router . push ( { name : 'home' , params : { id : '1' } } )  // Parameter receiving: this.$route.params.xxxxxxx

⚠️The difference between passing parameters

  • The query jump is matched with the route path attribute, the parameters are passed in plain text, and the parameters on the url are visible, and the parameters will not disappear after refreshing
  • Params route transfer with the route name attribute, the parameters are passed as cipher text, the parameters on the url are not visible, and the parameters will disappear after refreshing

Note that if you pass parameters through Params, the routing configuration path: “/home/:id” or path: “/home:id” will keep the refresh page id. If you do not configure the path, the refresh page parameters will disappear.

For others, please refer to [22.1 Routing parameters and receiving methods] (#221 Routing parameters and receiving methods)

15.2 Secondary routing

The routing configuration is as follows:

path: '/home',
name: 'Home',
component: () => import('../views/Layout/index'),
children: [
    {
        path: '/home',
        name:'home',
        component:() => import('../views/home/index')
    },
  	{
        path: '/home/user',
        name:'user',
        component:() => import('../views/user/index')
    }
]

explain:

When the address /homeis accessed , the ../views/Layout/indexcomponent is loaded for display. At this time the component is still nested in the route <router-view/>, then the component is loaded '../views/home/index'for display; when the address /home/useris accessed , the ../views/Layout/indexcomponent is loaded for display, but the routing part of the component is loaded '../views/user/index'for display Up.

to sum up:

  • Access /home../views/Layout/indexcomponent + routing '../views/home/index'component
  • Access /home/user../views/Layout/indexcomponent + routing '../views/user/index'component

Lesson 16

16.1 Local style and global style

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

In the style of the vue file, if scoped is set, it means that the current style is only effective in the vue file; if scoped is not set, it means that it is a global style.

16.2 Routing Menu

The routing menu can be set through the router.js file to this.$router.options.routesobtain routing information, and the corresponding information can be obtained through traversal. Examples are as follows:

const routes = [
    {
        path: '/login',
        name: 'Login',
        hidden: true,
        component: () => import('../views/Login/index'),
        meta: {
            name: '登录'
        }
    },
    {
        path: '/user',
        name: 'User',
        component: () => import('../views/Layout/index' ) , 
        meta : { 
            name : 'User Management' 
        } , 
        children : [ 
            { 
                path : "/userIndex" , 
                component : ( )  =>  import ( '../views/User/ index' ) , 
                meta : { 
                    name : 'User List' 
                } 
            } 
        ] 
    } 
]

Borrow elementUI to implement the navigation menu:

<el-menu  background-color="transparent" text-color="#fff" active-text-color="#fff" router>
    <template v-for="(item,index) in routers">
        <el-submenu v-if='!item.hidden' :key='index' :index="item.path">
            <!-- 一级菜单 -->
            <template slot="title">
                <i class="el-icon-location"></i>
                <span>{{item.meta.name}}</span>
            </template>
            <!-- 子级菜单-->
            <el-menu-item v-for='(subItem,index2) in item.children' :key="index2" :index="subItem.path">{{subItem.meta.name}}</el-menu-item>
        </el-submenu>
    </template>
</el-menu>

Note 1: By this.$router.options.routesobtaining routes, if the route does not need to generate a menu, it can be judged with custom attributes. For example, the hidden attribute is used to judge above, and the next level of routing information can be obtained through childen to generate a secondary navigation menu.

Note 2: Generally, we avoid using v-for and v-if at the same time. The solution adopted above is to nest v-if in v-for, and only need to write v-for on the template; otherwise, You can also nest v-for in v-if.

Lesson 17

17.1 SVG files

  1. The custom global component SvgIcon is main.jsregistered, see [17.2 Global component Vue.component] (#172 Global component Vuecomponent)
  2. Component template added
<svg :class="svgClass" aria-hidden="true">
   <use :xlink:href="name"></use>
</svg>
  1. Parse the svg file
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => {
  return requireContext.keys().map(requireContext)
}
requireAll(req)
  1. Configuration in Vue.config.json
module.exports = {	
	chainWebpack: (config) => {
        const svgRule = config.module.rule("svg");
        svgRule.uses.clear();
        svgRule
            .use("svg-sprite-loader")
            .loader("svg-sprite-loader")
            .options({
                symbolId: "icon-[name]",
                include: ["./src/components/icons"]
            });
    }
}

Note that you need to install dependencies:

$npm install svg-sprite-loader -S

The color of the svg file can not be set through the color attribute, but the fill attribute:

.svg-icon{
  fill: #fff;
}

/* Or you can specify to use the current color*/ 
. Svg-icon {
   fill : currentColor;
}

17.2 Global component Vue.component

Rules: Vue.component(‘组件名称’, ‘组件代码’)—— Component code is the code we write using vue files

There are two modes in vue3.0:

  • compiler (template) mode
  • Runtime mode-The default of the vue module is runtime mode, which points to the “dist/vue.runtime.common.js” location
// compiler (mode) template 
new  Vue ( { 
  el :  '#app' , 
  router :  router , 
  store :  store , 
  template :  '<App/>' , 
  components :  {  App  } 
} ) 
// runtime mode (runtime) 
new  Vue ( { 
  router , 
  store , 
  render :  h  =>  h ( App ) 
} ) . $mount ( "#app" )

If we want to use global components in vue3.0, we need to modify the default point of vue in config.js, which is to change to compiler mode- reference link :

module . exports  =  { 
   configureWebpack : ( config )  =>  { 
        config . resolve  =  {  // Configure the resolution alias 
           alias : { 
             'vue' : 'vue/dist/vue.esm.js' , 
           } 
        } 
   } 
}

17.3 prop / propsData

Props can be basic data or objects, used to receive data from the parent component. In the parent component, the child component 参数名=参数值can be passed directly in the form of, and the props can be used in the child component to obtain it.

// Parent component passes parameters
<template>
	<div>
    <child myParams='hello'></child>
  </div>
</template>

// The child component accepts parameters
<template>
	{{myParams}}
</ template >
 < script > 
export default {    	props : [ ' myParams ' ], setup ( props ){ // At this time props are also injected, you can directly print the console . log ( props . myParams )     }   } </ script >   

There are two ways to write props parameters:

// Ordinary writing just direct the array of parameter names 
props: [ 'iconClass' ,  'className' ]  // No restriction on data type

// Specify the data type writing 
props:  { 
  iconClass :  { 
    type :  String , 
    required :  true 
  } , 
  className :  { 
    type :  Array , 
    default :  ( )  =>  [ ] , 
    validator : ( value )  =>  { 
       return  value >= 0 ; 
    }   
  } 
}

Parameter description of the specified data type:

  • type (specified data type): String: string; Number: number; Boolean: Boolean; Array: array; Object: object; Date: date; Function: function; Symbol: unique value (ES6).
  • required (required): the default is false, if it is set to true, the parent must pass in data, otherwise an error will be reported.
  • default (default value): basic data type: direct assignment; object data type: use function assignment () => []
  • validator (verify whether the incoming value meets the rules): verification

17.4 watct/computed

computed (computed attribute)

// 2.0 - 普通写法
computed:{
  iconName(){ return this.name + 'icon' }
}
// 2.0 - get/set写法
computed:{
  iconName:{
    get(){ return this.name + 'icon' }
    set(){ this.name = 'newIcon' } 
  }
}

const count = ref(1)
// 3.0 - 普通写法
const plusOne = computed(() => count.value + 1)
// 3.0 - get/set写法
const plusOne = computed({
  get: () => count.value + 1,
  set: val => { count.value = val - 1 } 
} ) 
// Example 
plusOne . Value  =  2  
console . Log ( count . Value )  // 1, the above set set count.value to 1 
console . Log ( plusOne . Value )  // 2, at this time count.value is 1 , +1 is 2

watch (observed value change)

Two monitoring methods:

  • deep: deep monitoring, no matter how deep the data is nested
  • immediate: initial monitoring (simple understanding, monitoring when the component is loaded)
// 2.0 writing 
wacth:  { 
  myData :  { 
    handler ( newValue ,  oldValue ) { 
      console . Log ( newValue ) 
    } , 
    deep :  true , 
    immediate :  true 
  } 
} 
// 3.0 writing 
// Basic data 
watch ( myData ,  ( val ) = > { 
    console . log ( val ) 
} ) 
// object data 
watch (() => chooseItems.value, (val) => { console.log(val) } ) 
// Multiple monitoring 
watch ( [ 
  ( )  =>  cons . Page ,  
  ( )  =>  cons . PageSize ,  
  ( )  =>  query . Value 
] ,  ( [ val1 ,  val2 ,  val3 ] )  =>  { 
  console . Log ( val1 ,  val2 ,  val3 ) 
) )

17.5 Profile picture-center cropped image

<img src='' alt=''>
<style>
  img{
    width:100px;
    height:100px;
    border-radius:100px;
    object-fit: cover;
  }
</style>

The key is how the object-fit attribute specifies how the content of the element should adapt to the height and width of the specified container:

  • fill-default, does not guarantee to maintain the original ratio, the content stretches to fill the entire content container
  • contain-keep the original size ratio, the content is zoomed (show all, the extra part will be blank)
  • cover-keep the original size ratio, but part of the content may be cut (display part, the extra part will be cut)

Lesson 18

18.1 Vuex state management

5 parts

1. state —— store initialization data this.$store.state.xxxxx

2. Getters —— Secondary processing of data in State (filtering data is similar to filter) this.$store.getters.xxx

3. Mutations -all the methods to calculate the data are written in it, use this.$store.commit(‘mutationName’) when triggered on the page

4. modules —— Modular Vuex

5. actions (asynchronous)-The function of action is similar to that of mutation. They both change the state in the store, but there are two differences between action and mutation:

  • Actions mainly deal with asynchronous operations, mutations must be executed synchronously, and actions are not subject to such restrictions. In other words, in action, we can handle both synchronization (view triggers Action, and Action triggers Mutation) or asynchronous operations.

  • The action changes the state, and finally by submitting the mutation, this.$store.dispatch(actionName)

  • Role positioning is based on the sequence of processes, and the two play different roles. Mutation: Focus on modifying State, theoretically the only way to modify State. Action: business code, asynchronous request.

Modularity -Reference: Vuex Modular Use

export default new Vuex.Store({
  modules:{
    login,
    info,
    user
  }
})

// After modularization, you can add the module name 
this . $store . State . ModuleA . Name ; 
// getter, mutation, action are all registered in the global namespace by default, we can add namespaced: true when exporting the module making modules with namespace, can then be accessed by the module name, the specific detailed references 
the this . $ Store . getters [ 'ModuleA / the fullName' ] ;  
the this . $ Store . dispatch ( 'ModuleA / ASYNC_SET_NAME' ,  {  name : "JJ"  } ) ; 

18.2 Browser storage

1. cookie_js

$npm install cookie_js --save
// 储存
cookie.set('key', 'value');
cookie.set({ key1: 'value1', key2: 'value2' });

// 获取
cookie.get('key');
cookie.get(['key1', 'key2']);

// 清除
cookie.remove('key'); 
cookie.remove('key1', 'key2'); 
cookie.remove(['key1', 'key2']);

2. HTML5 book storage

  • sessionStorage (cleared when the browser is closed) Temporary

Storage size: 5M (data size); stored on the client; can only store string types; mainly store some relatively simple things, or small interactions;

// store 
window . SessionStorage . The setItem ( "Key" , "value" ) ; 
// get 
window . SessionStorage . GetItem ( "Key" ) ; 
// delete the 
window . SessionStorage . RemoveItem ( "Key" ) ; 
// clear all 
sessionStorage . clear ( ) ;

Note: Objects and strings need to be converted when accessing, JOSN.parse() string to object + JSON.stringify() object to string.

  • localStorage (manually clear) long-term;
// store 
window . LocalStorage . The setItem ( "Key" , "value" ) ; 
// get 
window . LocalStorage . GetItem ( "Key" ) ; 
// delete the 
window . LocalStorage . RemoveItem ( "Key" ) ; 
// clear all 
localStorage . clear ( ) ;

Lesson 19

19.1 Guard routing

Common use: the user enters the homepage, if not logged in, it will automatically jump to the login page.

Router . beforeEach ( ( to ,  from ,  Next )  =>  { 
   / ** 
    * to: incoming pages 
    * from: a page 
    * next: Page jump 
    * / 
} )

Note: Be sure to call the next method (that is, write the next method), otherwise the hook will not be resolved and may fall into an infinite loop.

  • next(): The parameter is empty, that is, the route object in to is executed, and the jump will not execute beforeEach, and the next jump with parameters will trigger beforeEach again

  • next(‘/’) or next({ path:‘/’ }): Jump to a different address. The current navigation is interrupted, and then a new navigation is performed. You can pass any location object to next, and you are allowed to set options such as replace: true, name:‘home’, and any options used in toprop or router.push of router-link.

  • next(error): If the parameter passed to next is an Error instance, the navigation will be terminated and the error will be passed to the callback registered by router.onError().

Token login detection example

/** 
* 1\. When directly entering a non-whitelist path such as index, the parameter to is changed to "/index", triggering the route pointing, it will run beforeEach 
* 2\. If the token does not exist and is not in the whitelist, Next points to login, the routing point occurs again, and beforeEach is run again, the parameter to is changed to "/login" 
* 3\. If the whitelist is judged to exist, execute next() directly. Because there is no parameter, it will not be beforeEach again. 
*/

const  whiteRouter  =  [ '/login' ] ;  // Set a whitelist 
router . beforeEach ( ( to ,  from ,  next )  =>  { 
    if  ( getToken ( ) )  { 
        // token exists 
        next ( ) 
    }  else  { 
        // token does not Existence-Jump to the login page 
        if  ( whiteRouter . IndexOf ( to . Path ) !== - 1 )  { 
            next()
        } else {
            next('/login')
        }
    }
})

19.2 Token login detection

Lesson 20

20.1 Callback $emit and modifier sync

The child component vm.$emit(eventName,arg)passes information to the parent component, and the parent component <child @eventName=""></child>receives it by listening to events. The modifier sync is syntactic sugar: the child component is passed this.$emit('update:foo', newValue), and the parent component was originally written <child :foo="bar" @update:foo="val => bar = val"></child>, but now it can be abbreviated by sync syntactic sugar <child :foo.sync="bar"></child>. The function of the vue modifier sync is: when a child component changes the value of a prop, the change will also be bound to the parent component.

// Subassembly
<template>
    <div>
         I am a subcomponent, and I am in the red ocean!
        <input type="button" value="点我隐身" @click="upIsShow">
    </div>
</template>
<script>
    export default {
        methods:{
            upIsShow(){
                this.$emit("update:isShow",false);
            }
        }
    }
</script>
// parent component
<template>
    <div>
        < input  type = " button "
                value = " I am the button in the parent component " 
               @ click = " show " >
      	<child :isShow.sync="isShow" v-show="isShow"/>
    </div>
</template>
<script>
    import child from "@/components/child"
    export default {
        data() {
            return {
                isShow:false
            }
        },
        components:{
            child
        },
        methods:{
            show(){
                this.isShow=true;
            },
            changeIsShow(bol){
                this.isShow=bol;
            }
        }
    }
</script>

Step by step abbreviated process:

  • <child @update:isShow="function(bol){isShow=bol}" v-show="isShow"/>
  • <child @update:isShow="bol=>isShow=bol" v-show="isShow"/>
  • <child :isShow.sync="isShow" v-show="isShow"/>

20.1 Global methods

The global approach helps to save code resources, without having to rewrite a lot of consistent code or only partially different code.

1. Global registration

// 1\. Create a method in the custom file toTop.js 
export  default  { 
  install  ( Vue ,  options )  { 
    Vue . Prototype . $toTop  =  function  ( )  { 
      console . Log ( 'Plugin Test' ) 
    } 
  } 
} 
// 2\. added to the global method main.js 
Import  toTop  from  './toTop' 
Vue . use ( toTop ) 
// 3\. global may be used 
the this . $ toTop ( )

2. On-demand introduction

// 1\. Create a method in the custom file toTop.js 
export  function  toTop ( )  { 
  console . Log ( 'Plugin Test' ) 
} 
// 2\. 
Import  { toTop }  from  './toTop' in the 
used file as needed // 3\. 
toTop ( ) can only be used after introduction

3. VUE3.0 method

// 1\. Create a method in the custom file 
export  function  myGlobal ( ) { 
	const  func1  =  ( ) => { } 
  const  func2  =  ( ) => { } 
  return  { func1 , func2 } 
} 
// 2\. Introduced in the used file 
import  myGlobal  from  './global.js' 
setup ( ){ 
  const  { func1 , func2 }  =  myGlobal ( ) 
  // func1 and func2 can be used below 
  func1 ( ) ; 
}

21st hour

slightly.

Lesson 22

22.1 Routing parameters and receiving methods

The first type: clear text reference

The URL path will show the passed parameters. Advantage: page refresh parameters will not be lost, disadvantage: parameter disclosure.

// Html跳转
<router-link :to="{name:xxx,query:{}}"></router-link>

// JS跳转
this.$router.push({
  name: `xxx`,
  query: {
  }
})

// Jump page to receive parameters
this.$route.query.xxxxxx

The second type: cipher text transfer parameters

The URL path does not show the passed parameters. Advantages: parameters are not displayed, disadvantages: page refresh parameters disappear.

// Html跳转
<router-link :to="{name:xxx,params:{}}"></router-link>

// JS跳转
this.$router.push({
  name: `xxx`,
  params: {
  }
})

// Jump page to receive parameters
this.$route.params.xxxxxx

The third type: passing parameters in colon form

Advantage: page refresh parameters will not be lost, disadvantage: need to be configured one by one.

// Routing configuration 
{ 
  path :  "/infoDetailed/:newsId/:newsTitle" , 
  name : "InfoDetailed" meta :  { 
    name :  "
   InfoDetailed
   " } , 
  component :  ( )  =>  import ( "../views/Info/ category.vue" ) 
}

// JS jump 
root . $router . Push ( { 
    path :  `/InfoDetailed/ ${ data . Id } / ${ data . Title } ` 
} )

// Jump page receives parameters 
$route . Params . NewsId 
$route . Params . NewsTitle

Fourth: vuex combined with HTML5 local storage

Advantages: parameters are not displayed, disadvantages: slightly overkill (to solve the second parameter loss)

The fifth type: a new window opens

rarely seen. Advantages: parameters are not displayed, disadvantages: slightly overkill (to solve the second parameter loss)

// Html jump-vue1 does not support, query/params are both 
< router-link  tag = "a"  target = "_blank" : to = "{name:'searchGoods',params:{}}" > Popular Goods < / router-link >

// JS Jump - Note that the function is resolve, not Push 
the let  RouteData  =  the this . $ Router . Resolve ( { 
   name :  "searchGoods" , 
   Query :  the params , 
   // the params: {} 
} ) ; 
window . Open ( RouteData . The href ,  '_blank' )

22.2 Rich Text Editor

Choose a third-party rich text editor to install, the following is an example- https: //www.npmjs.com/package/vue-quill-editor

installation:

$npm install vue-quill-editor --save

Introduce

import { quillEditor } from "vue-quill-editor";
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

use

<quillEditor v-model="form.content" ref="myQuillEditor" :options="data.editorOption"/>

Lesson 23

23.1 Componentization

The component in the page development is actually a part of the page composition, just like every component in a computer (such as hard disk, keyboard, mouse), it is an independent logic and function or interface, and at the same time can be carried out according to the specified interface rules Mutual integration into a complete application. A simpler understanding is to split the business logic of the page into small pieces and recombine them to form a complete system. When a component is not needed or you want to replace a component, you can replace and delete it at any time without affecting the operation of the entire application.

1. Why do you need component development, and what are the advantages?

**High cohesion: **The component function must be complete. If I want to implement the drop-down menu function, then in the drop-down menu component, only all the functions required by the drop-down menu are done.

**Low coupling: **Code independence will not conflict with other codes in the project.

The simple point is that in actual engineering, teamwork (multi-person joint development) is often involved. The traditional way of developing business lines to write code is easy to conflict with each other, because everyone may work in the same file. Therefore, component-based development can avoid this conflict, because everyone is responsible for different component development, so there will be no change to other people’s code, and each component has clear responsibilities and complete functions. The functions of each tube are convenient for unit testing and reuse.

Advantage:

  1. Improve development efficiency: After a component is developed, if the functions in other places are the same, just load the component directly, which is convenient and fast;
  2. Convenient for repeated use: once development, multiple use;
  3. Simplify debugging steps: only debug the current component and have nothing to do with other business logic. After using the same component on many pages, if the component has a BUG, ​​then all references are BUG, ​​one fix, that is, all fixes;
  4. Improve the maintainability of the entire project: independent maintenance of components, strong management; maintenance does not affect other business logic;
  5. Facilitate the collaborative development of multiple people: multi-person development, each person is responsible for their own developed components, and will not modify other people’s code; avoid code mistakes;

2. Component type

  1. Page-level components: Page-level components, usually .vue components in the views directory, are a large page that composes the entire project. Generally, there will be no external interface.
  2. Business-reusable basic components: components that are reused by each page in the business. This type of component is usually written in the components directory and then used in each page through import.
  3. Independent components not related to business: Independent components not related to business functions. Such components are usually used as basic components in various business components or page components. Components included in the popular ElementUI and iview on the market are all independent components. If it is a self-defined independent component, such as a rich text editor, it is usually written in the utils directory.

3. Three elements of components:

  1. Prop: used to define the properties of the component (component property parameters).
  2. Event: A custom event is used to trigger the component’s event (the parent component method is often called back).
  3. Slot: Used to extend the function of the component. (Slot), the content of the parent component is transferred to the child component and displayed in the child component

4. Define components

// global components 
// Register of global components, in vue project .vue page will mount this component, a little waste of resources 
Vue . The Component ( 'Child-the Component' ,  { 
    Template :  ` 
    <div> 
        <slot> 
            <the p-> If the parent component is useless to insert content, I will appear as the default</p> 
        </slot> 
    </div>` 
} ) ;

// Partial components 
// Loaded on demand, only referenced in the .vue pages that need it, without wasting resources, just a little troublesome 
import  Users  from './ components / Users '

23.2 Life Cycle

Note: Watch will only be executed when the data changes, and the created() phase is before the data is instantiated. At this time, changing the data in data() will not trigger the change event and cannot enter the watch code part, but the mounted() phase After the data is instantiated, changing the data in data at this time will trigger the change event, which can also be watched.

23.3 v-slot slot

1. Anonymous slot-not specified, show all

In the following example, in the rendering, the slot will be replaced with the slot content hello in the parent component. Note that several slots in the child component will display several slot contents:

<!-- parent component.vue --> 
< child >hello</ child >
 <!-- child component.vue --> 
< template >
	<div>
    	<slot></slot>
    	<slot></slot>
  </div>
</template>

2. Named slot-designated name display

In the following example, during rendering, slot will be replaced with the slot content of the corresponding name in the parent component:

<!-- Parent component.vue --> 
< child >
  <template v-slot:header>
			header
  </template>
  <template v-slot:main>
			main
  </template>
</ child >
 <!-- child component.vue --> 
< template >
	<div>
    	<slot name='header'></slot>
    	<slot name='main'></slot>
  </div>
</template>

3. Scope slot-data binding, communication between parent and child components (commonly used in componentization)

In the following example, the parent component obtains the properties bound to the slot by binding the slot prop-slotProps, so that the parent component obtains the value of the child component. Note that if it is a named slot, the following v-slot: default Need to be changed to v-slot: the corresponding slot name:

The name attribute of the child component v-slot:namecorresponds to the name used in the parent component , and the attribute in the child component is accessed through v-slot:namethe value set in the parent component :

<!-- Parent component.vue --> 
< current-user >
  <template v-slot:slotName="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</ current-user >
 <!-- Subcomponent.vue --> 
< span >
  <slot v-bind:user="myUser" :name='slotName'>
    {{ myUser.lastName }}
  </slot>
</span>

For details, see User module and table component-index.vue

23.4 Component business logic split

For details, see table component-index.vue and tableLoadData.js

Use mixin in 2.0 :

Mixin is a very flexible way of distributing reusable functions in Vue components . The mixin object can contain any component options. When a component uses a mixed-in object, all the options of the mixed-in object will be mixed into the options of the component itself. Mixin can be simply understood as a common function encapsulation, imagine encapsulating the JS method.

// Define a mixin object. 
js var  myMixin  =  { 
    created : function  ( )  { 
        this . Hello ( ) 
    } , 
    methods : { 
        hello : function  ( )  { 
            console . Log ( 'hello from mixin!' ) 
        } 
    } 
}

// definition of an object using the mixed components 
var  the Component  =  Vue . Extend ( { 
    as mixins : [ myMixin ] 
} )

Option merge

1. In the mixed data, if the key name is the same, the key name in the component is read ; otherwise, the mixed key name is read;

2. Hook: Hook functions with the same name will be mixed into an array, so all will be called. The hook of the mixed object will be called before the hook of the component itself .

3. The value is mixed into the object: such as methods, components, etc., the options will be merged, and the component object covers the mixed-in object.

Lesson 24

24.1 JSON object copy

1. Deep copy (understanding in vernacular) -JSON.stringify (object);

Direct copy of the original object of all data, and out of the original object; will not affect the original object; Note: deep copy of the object is out of the string type .

2. Shallow copy (understanding in vernacular) -Object.assign({}, object);

Only copy of the original object data of a first layer, the second layer, and the reference data or the original data object; NOTE: shallow copy of the object is out of the object type

3. Recursive method (understanding in vernacular) not mentioned in the video

Loop through the object once, no matter how deep the level is, all key objects are assigned to the new object and separated from the original object; it will not affect the original object; this method can effectively solve the loss of function, undefined, and Symbol() of deep copy Question; Note: The traversed object is what it is, and it remains unchanged

24.2 Component communication (important)

Component relationship:

  • Parent-child components: A and B, B and C, B and D, C and E, D and E

  • Descendants: A and D, B and E

  • Brother components: C and D

  • Intergenerational components: A and E

Method 1: parent and child component communication props, emit, .sync

// The following "property name" and "method name" should correspond one by one
// Parent component.vue
<template>
    <B :属性名.sync="myData“ @方法名=“myFunc” />
</template>
<script>
  import {reactive} from '@vue/composition-api'
  export default {
    setup(props) {
      const myData = reactive({})
      myFunc = (number) => {}
      return {myData, myFunc}
    }
}
</script>

// Subcomponent. vue 
<template> 
    <div>{{ data }}</div> 
</template> 
<script> 
export default { 
    props: { 
        property name: { 
            type: String, 
            default:  " "
         } 
    }, 
    setup (){ 
        emit("method name", 100) // method of callback parent component 
        emit("update:property name", 111111) 
    } 
} 
</script>

Method 2: Central event bus-communication between components at all levels

// bus.js - Create instance 
Import  Vue  from  'VUE' ; 
Export  default  new new  Vue ( ) ;

// call the event 
Import  Bus  from  'bus.js' 
Bus . $ EMIT ( 'getTarget' ,  'the Hello world!' ) ;

// 注册事件
import Bus from 'bus.js'
Bus.$on('getTarget', target => {  
    console.log(target);  
}); 

Method 3: Vuex

Slightly, see the vuex section for details.

Method 4: $attrs, $listeners

  • $attrs is passed from the outer component to the inner component

For example: A component nests B, B component nests C; A transfers attributes to B, B can be obtained through this.$attrs, and to continue to be passed to the next layer, it needs to be bound to the next layer of components. v-on='$attrs'Note if B receives the attribute of the same name through props, and this.$attrs cannot read the attribute of the name at this time and in the subsequent. The $listeners transfer method is the same.

Method 5: provide, inject-communication between cross-level components

// The ancestor component provides variables through the provider, and then injects the variables in the descendant components through inject 
// Parent component 
provide ( "customVal" ,  "I am the value passed by the parent component to the child component" ) ; 
// Child component 
inject ( "customVal" ) ;  // get through this.customVal

Method 6: $parent, $children

Slightly, I feel less useful.

Lesson 25

25.1 Dynamic routing

Default routing (accessible to any role) and dynamic routing (access permissions assigned by role) can be set in the routing file, user roles are determined in the routing guard and routing permissions are dynamically assigned. See guard.js for details .

25.2 Custom instruction

To achieve the needs of displaying buttons with different permissions, in addition to [global method] (#201 global method) (that is, by registering a global method, v-if calls the method in the button and passes in parameters to determine whether to display), but also It is achieved by using custom instructions.

5 states of custom instructions (manipulate DOM elements)

  • bind: It is called only once, when the instruction is bound to the element for the first time. This hook can be used to define an initialization action that is executed once when binding.
  • Inserted: Called when the bound element is inserted into the parent node (the parent node can be called, it does not need to be in the document)
  • Update: Called when the template that is bound to the element is updated, and regardless of whether the binding value has changed, by comparing the binding value before and after the update, unnecessary template updates are ignored
  • componentUpdate: called when the template of the bound element completes an update cycle
  • Unbind: only called once, called when the instruction element is unbound
// 通过v-hello使用即可
Vue.directive("hello",{
  bind:function(el,bingind,vnode){
      el.style["color"] = bingind.value;
      console.log("1-bind");
  },
  inserted:function(){
      console.log("2-insert");
  },
  update:function(){
      console.log("3-update");
  },
  componentUpdated:function(){
      console.log('4 - componentUpdated');
  },
  unbind:function(){
      console.log('5 - unbind');
  }
})

Pay attention to the custom instructions and don’t forget to introduce them in main.js.

Lesson 26

26.1 keep-alive component cache

Vue has built-in components that can retain DOM elements in memory during component switching, prevent repeated rendering of DOM, and improve performance.

Original route:

<router-view></router-view>

How to increase the cache:

<keep-alive> 
     <!--需要缓存的-->
    <router-view v-if="$route.meta.keepAlive"></router-view> 
</keep-alive> 
<!--不需要缓存的-->
<router-view v-if="!$route.meta.keepAlive"></router-view>

Attributes:

  • include: string or regular expression, only components with matching names will be cached
  • exclude: string or regular expression, components with matching names will not be cached
  • max: number, how many component instances can be cached at most

keep-alive related hook function activated

activated is called when the keep-alive cached component is activated, and the deactivated function is called when the keep-alive cached component is deactivated. The order of the life cycle: created-mouted-activated.

26.2 404 page

Add the following configuration to the default route, * refers to other matched paths, which are redirected to 404. Note that the general 404 configuration is put at the end:

[{
    path: '/404',
    name: 'page404',
    hidden: true,
    component: layout,
    children: [
        {
            path: '/404',
            component: () => import('../views/404')
        }
    ]
},
{
    path: '*',
    redirect: '404',
    hidden: true
}]

If you use dynamic routing, you need to put * matching in the dynamic routing matching, and then put it to the last item when dynamically assigning.

Lesson 27

Nothing.

Lesson 28

For specific operations, please refer to the video tutorial: Tutorial-1 Tutorial-2 Tutorial-3

28.1 Server

28.2 Nginx installation

  1. Connect and enter the server
$ssh root@server address
  1. nginx installation
// Installation:
 $yum install nginx
// uninstall
$yum remove nginx
// Check if the installation is successful
$nginx –v
// View file location
$nginx –t
// Specify the configuration file-subsequent configuration operations will focus on it
$nginx -c directory
// stop
$nginx -s stop
// drop out
$nginx -s quit
// Restart loading configuration
$nginx -s reload

28.3 CentOS7 firewall

Basic operation:

Start: systemctl start firewalld.service

停止:systemctl stop firewalld.service

重启: systemctl restart firewalld.service || firewall-cmd –reload

Turn on boot: systemctl enable firewalld

Prohibit booting: systemctl disable firewalld

View firewall status: firewall-cmd --state

Port operation:

View the open ports: firewall-cmd --list-ports

Open ports: firewall-cmd --zone=public --add-port=80/tcp --permanent

Close the port: firewall-cmd --zone=public --remove-port=3338/tcp --permanent

Query whether a port is open: firewall-cmd --query-port=80/tcp

Restart the firewall: firewall-cmd --reload

28.4 iptables configuration

Note: The default in CentOS 7 is the firewalld firewall. If you use iptables, you need to turn off the firewalld firewall (1. Turn off the firewall, 2. Cancel startup).

#Close the firewall systemctl stop firewalld

#Cancel startup systemctl disable firewalld

#View status firewall-cmd --state

Install iptables:

Check whether it is installed: service iptables status

Install iptables: yum install -y iptables

安装iptables-services:yum -y install iptables-services

Register iptables service: systemctl enable iptables.service

Start the service: systemctl start iptables.service

View status: systemctl status iptables.service

Iptables configuration:

#Configure filter table

Allow connected packets to enter

Allow newly-connected tcp packets on port 22 80 443 to enter

iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT

iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT

28.5 nginx configuration

proxy_pass

  • When there is a / at the end of the url in the proxy_pass configuration, nginx forwarding will remove the original url from the loc with / when the content of the matching expression is spliced ​​after the url in proxy_pass.
  • When there is no / at the end of the url in the proxy_pass configuration, if the url does not contain the path, the original url is directly spliced ​​after the url in the proxy_pass; if the url contains the path, the content after removing the location matching expression from the original uri is spliced ​​in proxy_pass After the url in.
// Example-Test address: http://www.web-jshtml.cn/productapi/getSms/

// 1\. There is / hour at the end of the url in the configuration. The 
actual access address after proxy: http://www.web-jshtml.cn/api/getSms/; 
location ^~ /productapi/ { 
    proxy_pass  http : //www.web-jshtml.cn/api/; 
} 
// Actual access address after proxy: http://www.web-jshtml.cn/getSms/; 
location ^~ /productapi/ { 
    proxy_pass  http : //www.web-jshtml.cn/; 
} 
// Actual access address after proxy: http://www.web-jshtml.cn//getSms/; 
location ^~ /productapi { 
    proxy_pass  http : / /www.web-jshtml.cn/; 
} 
// Actual access address after proxy: http://www.web-jshtml.cn/api//getSms/; 
location ^~ /productapi { 
    proxy_pass  http : //www. web-jshtml.cn/api/; 
}

// 2\. There is no / at the end of the url in the configuration 
// Actual access address after proxy: http://www.web-jshtml.cn/productapigetSms/; 
location ^~ /productapi/ { 
    proxy_pass  http : //www.web-jshtml.cn/productapi; 
} 
// Actual access address after proxy: http://www.web-jshtml.cn/api/getSms/; 
location ^~ /productapi { 
    proxy_pass  http : //www.web-jshtml.cn/api; 
} 
// Actual access address after proxy: http://www.web-jshtml.cn/productapi/getSms/; 
location ^~ /productapi/ { 
    proxy_pass  http : //www.web-jshtml.cn; 
} 
// Actual access address after proxy: http://www.web-jshtml.cn/productapi/getSms/; 
location ^~ /productapi { 
    proxy_pass  http : / /www.web-jshtml.cn; 
}

Location matching rules

Identifierdescription=Exact match ; before used in standard url, the request string and url are strictly matched. If the match is successful, stop the match and immediately execute the request in the location.~Regular match ; used before regular url, it means that uri contains regular and is case sensitive.~*Regular matching ; used before the regular url, it means that the uri contains regular and is not case sensitive.^~Non-regular matching ; before the standard URL, the nginx server will end after matching the uri with the most prefixes. After the pattern is successfully matched, regular matching will not be used.noOrdinary matching (the longest character matching) ; it has nothing to do with the location order, and the matching result is taken according to the length of the match. If it matches exactly, stop the match.

Priority- The matching order for multiple location configurations is: first exact match =; secondly prefix match ^~; secondly match according to the regular in the configuration file; then match prefix matching without any modifiers; finally handed over to / general match;

// Example 
location  = / {   
   //exact match/, no string 
    echo  "rule A" after the host name ; 
} 
location  = /login { 
  //exact match/login start address, after the match is met, do not continue Next search for 
    echo  "rule B" ; 
} 
location ^~ /blog/  {  
  //Non-regular matching, after matching /blog/, stop searching down regular, use this 
  echo "Rule C" ; 
} 
location ~ \ . ( Gif | jpg | png | js | css ) $  { 
    //If the case-sensitive regular matching is successful, stop searching for regular regulars and use this 
    echo  "rule D" ; 
} 
location ~* \ . png$  {   
   //Case-sensitive regular matching, stop searching down regular, use this 
    echo "Rule E" ; 
} 
location / { 
  //Because all addresses start with /, this rule will match all requests 
  //If no rule matches, this rule will be used 
    echo  "Rule F" ; 
} 
location / blog / detail  {  
  //The longest string match, if the complete match is successful, the match will not continue, otherwise the regular match will be 
  echoed "Rule G" ; 
} 
location / images  {   
    //Longest string match, same as above 
    echo "Rule Y" ; 
} 
location ^~ /static/files  {   
    //Non-regular matching, if the matching is successful, it will not continue to match 
    echo "Rule X" ; 
}

// When accessing the root path/, such as http://www.web-jshtml.cn/, rule A will be matched. 
// When visiting http://www.web-jshtml.c/login, rule B will be matched. 
// When visiting http://www.web-jshtml.c/login.html, rule F will be matched. 
// When visiting http://www.web-jshtml.c/blog/detail/3.html, rule C will be matched. -Find by matching priority

rewrite redirect

Command syntax:rewrite regex replacement [flag];

characterdescription\Mark the following character as a special character or a literal character or a back reference^Match the starting position of the input string$Match the end position of the input string*Match the preceding character zero or more times+Match the preceding string one or more times?Matches the preceding string zero or one time.Match all single characters except “\n”(pattern)Match the pattern in parentheses

The last flag parameter of rewrite:

Mark symbolDescriptionlastAfter this rule is matched, continue to match the new location URI rule downwardbreakThis rule is terminated after the matching is completed, and no rule is matchedredirectReturn 302 temporary redirectpermanentReturn 301 permanent redirect

// Example: 
// indicates that the jump is performed after the match is successful, and the permanent 301 jump is executed 
rewrite ^/ ( . * ) Http: //www.web-jshtml.cn/ permanent;    

Lesson 29

29.1 Summary

29.2 Vue2.0 reset

Basic template (method uses this.XXX; data uses this.XXX):

export  default  { 
    name : "vue2.0_example" , 
  	components : { } , 
  	props : { } ,  // Use props in other places directly through this.XXX 
    data ( )  { 
        return  { 
            myData : 0 
        } 
    } , 
  	computed : { 
      myData ( ) { 
        return  XXX ; 
      } 
    } , 
  	watch : { 
    	a ( val ,  oldVal ) { // Ordinary watch monitors the 
         console . log ( "a: " + val ,  oldVal ) ; 
     	} , 
     	b : {  // In-depth monitoring, you can monitor the changes of objects and arrays 
         handler ( val ,  oldVal ) { 
             console . Log ( " bc: " + val . c ,  oldVal . c ) ; 
         } , 
         deep : true  // true in-depth monitoring, 
         immediate : true  // initial monitoring 
     	} 
    },
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    methods: {
        myFunc() {}
    },
}

other

1. Summary of daily and weekly reports

It is recommended to develop the habit of writing daily newspapers so that it is easier to write weekly reports.

  • Weekly report content:
  • 1、… 2、… 3、…
  • Summary weekly report:
  • 1. What did you do this week? 2. The performance reflected in the project? 3. Problems encountered in development and solutions and ideas?
  • Technical difficulties: how to overcome these difficulties?
  • Business communication: business ideas, suggestions
  • Project ideas: own insights, constructive suggestions, etc. on the project

2. Project Management

Different branches of git warehouse can be recorded for management:

Lesson summary

  • The first semester understands the product development process from 0 to 1, product manager, UI designer, R&D department, test engineer

  • In the second class, install node.js, vue3.0 scaffolding, create github code management warehouse, build vue project

  • The difference between 2.0 and 3.0, vue.config.js, introduction of global style, router redirection, elementui dependency, git command to submit files

  • The 4th class hour Vue file standard structure, v-for traversal, key, v-bind attributes, @click event, binding class, basic data type, reference data type difference

  • Familiar with element-ui components, making form validation, and understanding the usage of components

  • The 6th class is the difference between package verification js file, webpack directory configuration pointing, export exposure method, import reference, command v-show, v-if

  • The 7th class hour 2.0 syntax to 3.0, setup function, reactive function, ref function, isRef, toRefs method

  • The 8th class hour axios interceptor, module management API, the difference between export and export default

  • 9th class hour Axios cross-domain configuration, environment variables, interface documents

  • The 10th class hour logs in to the interface for debugging, response interception, elementui message, root parameters

  • 10-1 hour login interface for debugging, response interception, elementui message, root parameters

  • The 11th class is based on the test case process development project, registration interface joint debugging, countdown setTimeout, setInterval, timeout timeout, login interface debugging, timer knowledge points

  • Twelfth semester understand the basic Promise methods, resolve, reject, all, race, then, catch

  • 13th class: Request header interception, Request Headers adding parameters, login password sha1 encryption, front-end encryption process, code optimization packaging method

  • The 14th class hour briefly understand the vue learning objectives, what to learn specifically, and understand the basic instructions

  • 15th class hour: background homepage construction, router routing jump, children attribute, components component, partial component introduction

  • In the 16th class, elementui’s el-menu component generates routing menus, defines global elemenui style sheets, and modifies group styles

  • 17th class hour svgIcon production, global component Vue.component, parent-child component pass value props, propsData, calculated properties computed

  • 18th class Vuex, State, Getters, Mutations, menu navigation collapse and expand

  • 18-1 hour cookie storage, sessionStorage storage, localStorage storage, JSON.parse, JSON.stringify

  • 18-2 class hour Vuex action asynchronous, synchronous, modules module management status data

  • The 19th class hour router.beforeEach routing guard, detects whether toKen enters the background illegally, to, from parameters, next method, Vuex namespace

  • The 19-1 class hour logs in and stores the token, and the token has basic logic to enter the background

  • In the 19-2 class, exit the background to clear the token, prevent illegal entry, merge GIT code, and submit the code developed on the day

  • The 20th class design draft UI production, element-ui component, el-select, el-row, el-col, el-button

  • 20-1 class design draft UI production, element-ui component, el-table, el-pagination

  • 20-2 class design draft UI production, element-ui component, el-dialog, parent-child component callback emit, decorator sync, vue2.0, 3.0 writing, watch

  • 20-3 class hour design draft UI production, element-ui component, el-messageBox, custom global method export install, VUE3.0 component renaming, watch

  • 20-4 class hour design draft UI production, information classification UI production

  • 21st class information management module, first-level classification interface, access classification interface, onMounted, related optimization

  • 21-1 Class hour information management module, delete interface, modify interface

  • 21-2 class hour interface encapsulation, vue3.0 encapsulation method, vuex actions method, convenient for later maintenance

  • Add information interface, get list interface, paging processing request data, get classification optimization, variable optimization for 21-3 class hours

  • 21-4 class hour record, batch delete interface, table component data loading optimization, formatter attribute return value, date component configuration data format, filter condition processing

  • 21-5 class information edit interface, add child classification interface, request all classification interface

  • 21-6 class hours prototype learning, prototype version view, GIT command control code version iteration, merge code, create new branch

  • 22nd class: router routing jump, 5 parameter transfer methods, vuex with HTML5 local storage

  • 22-1 class hour detailed page data reading, initialization data, rich text editor, vue devTool dependency

  • The 22-2 class hour elementui upload component combined with Qiniu Cloud third-party storage, Qiniu Cloud establishes space, domain name binding, and resolution

  • 22-3 class hours: ElementUI component secondary packaging development, thinking about some problems of component packaging, when do you need a watch, and passing parameter dynamic configuration data

  • The 23rd hour user management function iteration, git branch creation, daily report in daily work, weekly report summary, project management

  • 23-1 class hour User management UI production, elementUI el-select component packaging, parameter configuration, component naming conflict

  • 23-2 class hours Really understand vue component development, component concepts, advantages, global component component, local component import, and solve BUG from the source

  • 23-3 class hours vue life cycle, component life cycle, 3.0 rewrite 2.0 component

  • 23-4 class hours vue3.0 life cycle, encapsulating el-table components

  • Package el-table component in 23-5 hours, v-slot slot 3 ways, data binding

  • 23-6 hours encapsulate el-table components, data request, integrate URL request address, unified api folder management

  • 23-7 class hours encapsulate el-table components, split and combine business logic

  • 23-8 class hours elementUI page number components, business logic split page number, configuration items

  • 23-9 class hour vue2.0 mixins mixing, on-demand mixing, global mixing

  • The 24th semester hour, province, city, district, street component packaging, business logic extraction

  • 24-1 class hour Province, city, district, street component packaging, business logic extraction

  • 24-2 class hour, provincial and urban data return, el-radio, el-checkbox, access to role management API

  • 24-3 class hour user add interface, deep copy of json object, shallow copy usage and precautions

  • Chapter 24-4 Beginning of Class Component Communication. Sync, elemntUI Switch component, user list, delete interface joint debugging

  • The full version of the 24-5 class hour component communication (key knowledge)

  • User status interface, edit interface, search interface joint debugging for the 24-6th hour (on)

  • User status interface, editing interface, search interface joint debugging for the 24-7th class (part 2)

  • The 25th class hour is the development of dynamic routing, the routing is distributed by the system, and the system list interface

  • 25-1 class hour dynamic routing development, routing is assigned by role

  • 25-2 class hour button level permissions

  • 25-3 class hour button level permissions, custom command processing

  • Component cache keep-alive, interface optimization to avoid waste of resources

  • 26-1 class hour BUG repair, monitoring routing changes, environment variable parameter configuration

  • 26-2 class hour 404 page

  • Fix the 404 page problem of the 26-3 class hour, exit the interface joint debugging

  • The 27th class hour BUG repair process, priority ranking, project process stage

  • 28th credit hour ECS cloud server purchase, understanding of server infrastructure, nginx installation, port configuration, firewall

  • 28-1 class hours nginx configuration, multi-project deployment, single-project deployment, iptables installation and configuration

  • 28-2 class hours nginx configuration, log view, proxy_pass points to configuration, call interface data, domain name resolution access project


If you find any errors in this project, please submit issues for correction.

Download Details:

Author: MrEnvision

Source Code: https://github.com/MrEnvision/vue-admin

#vue #vuejs #javascript

Vue3.0 Basic Learning Project-simple Background Management System
6.30 GEEK