Shangpinhui project notes

2021/12/2
1. vue file directory analysis

public folder: static resources. When webpack is packaged, it will be packaged into dist folder intact.

pubilc/index.html is a template file, which is used to generate the entry file of the project. JS and CSS packaged by webpack will also be automatically injected into the page. When our browser accesses the project, it will open the generated index.html by default.

src folder (programmer code folder)

assets:  Store public static resources
components:  Non routing component (global component), other components are placed in views perhaps pages Folder
App.vue:  Unique heel component
main.js:  Program entry file, the first file to execute

babel.config.js: configuration file (babel related)
package.json: detailed information record of the project
package-lock.json: cache file (source of various packages)
2. Project configuration
2.1 When the project is running, the browser opens automatically

package.json
    "scripts": {
    "serve": "vue-cli-service serve --open",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
    },

2.2 close the eslint verification tool (there will be various specifications if it is not closed, and an error will be reported if it is not in accordance with the specifications)

  • Create vue.config.js under the root directory for configuration
module.exports = {
  //Close eslint
  lintOnSave: false
  }

2.3 configure the alias in src folder, create jsconfig.json, replace src / with @ /, and exclude indicates that the file with the alias cannot be used

 {
    "compilerOptions": {
        "baseUrl": "./",
            "paths": {
            "@/*": [
                "src/*"
            ]
        }
    },

    "exclude": [
        "node_modules",
        "dist"
    ]
 }

3. The style of the component page uses the less style, which is not recognized by the browser and needs to be downloaded
npm install --save less less-loader@5
If you want the component to recognize the less style, set it in the component
<script scoped lang="less">

4. Clear vue page default style
vue is a single page development. We only need to modify the index.html file under public

<link rel="stylesheet" href="reset.css">

5. Create the pages folder and create the routing component

5.1 create a router folder, create index.js for routing configuration, and finally introduce registration in main.js

5.2 summary
Differences between routing components and non routing components:

  • Non routing components are placed in components, and routing components are placed in pages or views
  • Non routing components are used through labels, and routing components are used through routing
  • Register to play routing in main.js, and all routing and non routing components will have the $router $route attribute
  • $router: generally, programmed navigation is used for route jump
  • $route: generally obtain route information (name, path params, etc.)

5.3 route jump mode

  • For declarative navigation, the router link tag can be understood as an a tag, which can also be modified by class
  • Programming navigation: declarative navigation can be done programmatically, and it can also handle some business

6. Display and hide of footer component

  • The footer does not exist on the login registration page, so it should be hidden, v-if or v-show
  • v-show is used here because v-if will frequently manipulate dom elements, which will consume performance. v-show only displays or hides elements through styles
  • When configuring a route, you can configure meta information meta for the route,
  • Define the show attribute in the original information of the route to assign a value to v-show and judge whether to display the footer component

7. Routing parameters
7.1,query,params

  • query and params can pass parameters
    query parameter: it is not part of the path. It is similar to the get request. The address bar is / search? K1 = V1 & K2 = v2
    Route information path corresponding to query parameter: "/ search"
    params parameter: part of the path. It should be noted that when configuring the route, it needs to occupy space. The address bar is displayed as / search/v1/v2
    The route information corresponding to the params parameter should be modified to path: "/search/:keyword". The /: keyword here is a placeholder for the params parameter
  • params parameter transfer problem
    (1) How to specify whether the params parameter can be passed or not
  If routing path Request delivery params parameter,But no delivery,You will find the address bar URL Yes, details are as follows:
  Search Of routing items path It has been specified to pass one keyword of params Parameters, as follows:
  path: "/search/:keyword",
  Execute the following code for route jump:
  this.$router.push({name:"Search",query:{keyword:this.keyword}})
  The current jump code was not passed params parameter
  Address bar information: http://localhost:8080/#/?keyword=asd
  There is less address information at this time/search
  Normal address bar information: http://localhost:8080/#/search?keyword=asd
  Solution: you can change path To specify params Parameters can be transferred or not 
  path: "/search/:keyword?",?Indicates whether the parameter can be passed or not

Reference connection: https://blog.csdn.net/weixin_44867717/article/details/109773945
(2) It can be seen from (1) that params can be transmitted or not, but how to solve if the transmitted space-time string.

 this.$router.push({name:"Search",query:{keyword:this.keyword},params:{keyword:''}})
 The problem is the same as that in 1,Address information is missing/search
 Solution: Join||undefined´╝îWhen the parameter we pass is an empty string, the address bar url It can also remain normal
 this.$router.push({name:"Search",query:{keyword:this.keyword},params:{keyword:''||undefined}})

(3) Can the routing component transfer props data?
Yes, but only params parameters can be passed. The specific knowledge is props attribute.
7.2 parameter transmission method

  • String form
    This. $router. Push ("/ search / + this. Params pass parameter +"? k="+this.query pass parameter)
  • Template string
    this. r o u t e r . p u s h ( " / s e a r c h / + router.push("/search/+ router.push("/search/+{this.params}? k=${this.query}")
    Note: it can be seen from the parameter passing method of the above string that the params parameter is combined with '/', and the query parameter is combined with '/'? combination
    http://localhost:8080/#/search/asd?keyword=asd
    asd in the above url is the value of params, and keyword=asd is the value passed by query.
  • Object (common)
    this.$router.push({name: "route name", params: {pass parameter}, query: {pass parameter}).
    When passing parameters in object mode, if we use params in passing parameters, we can only use name, not path. If we only use query to pass parameters, we can use path.

8. If you execute the same push multiple times, a warning will appear on the console
For example, when using this.$router.push({name: 'Search', params:{keyword: "..." ||undefined}), if the same push is executed multiple times, a warning will appear on the console.

let result = this.$router.push({name:"Search",query:{keyword:this.keyword}})
console.log(result)

Execute the above code once:

Multiple execution warnings:

Reason: push is a promise. Promise needs to pass success and failure parameters. We don't pass them in push.
Method: this.$router.push({name: 'Search', params:{keyword: "..." ||undefined}, () = > {}, () = > {}) the last two items represent the successful and failed callback functions respectively.
This way of writing will cure the symptoms but not the root causes. In the future, there will still be similar errors in programming navigation by pushing|replace in other components
push is a method of VueRouter.prototype. You can rewrite this method in the index in the router (it doesn't matter if you don't understand it. This is the front-end interview question)

//1. First, save a copy of the push of the vueroter prototype object
let originPush = VueRouter.prototype.push;
//2. Rewrite push replace
//The first parameter: tell the original push, the target location of the jump and which parameters are passed
VueRouter.prototype.push = function (location,resolve,reject){
    if(resolve && reject){
        originPush.call(this,location,resolve,reject)
    }else{
        originPush.call(this,location,() => {},() => {})
    }
}

9. Define global components
Our three-level linkage component is a global component, and the global configuration needs to be configured in main.js

//Register the three-level linkage component as a global component
import TypeNav from '@/pages/Home/TypeNav';
//The first parameter: global component name, and the second parameter: global component name
Vue.component(TypeNav.name,TypeNav);

Use this global component in the Home component

<template>
<div>
<!--  The three-level linkage global component has been registered as a global component, so it does not need to be imported-->
  <TypeNav/>
</div>
</template>

Global components can be used directly in any page without importing declarations
All the following commodity categories are three-level linkage components

Code change to achieve automatic page update

vue.config.js file settings in the root directory

module.exports = {
    //Close eslint
    lintOnSave: false,
    devServer: {
        // True means hot update, false means manual refresh, and the default value is true
        inline: false,
        // development server port 8000
        port: 8001,

    }
}

10. Other components of Home page
home folder index.vue

<template>
<div>
<!--  The three-level linkage global component has been registered as a global component, so it does not need to be imported-->
  <TypeNav/>
<!--  Carousel chart list-->
  <ListContainer/>
<!--  Recommended today-->
  <Recommend/>
<!--  Product ranking-->
  <Rank/>
<!--  Guess you like it-->
  <Like/>
<!-- floor -->
  <Floor/>
  <Floor/>
<!--  trademark-->
  <Brand/>
</div>
</template>

<script>
import ListContainer from './ListContainer'
import Recommend from './Recommend'
import Rank from './Rank'
import Like from './Like'
import Floor from './Floor'
import Brand from './Brand'
export default {
  name: "index",
  components: {
    ListContainer,
    Recommend,
    Rank,
    Like,
    Floor,
    Brand,
  }
}
</script>

<style scoped>

</style>

Encapsulating axios

axios Chinese document, including details.
https://www.kancloud.cn/yunye/axios/234845
Create the api folder in the root directory and create the request.js file.
The contents are as follows. The current document code is still relatively small. You can add content if you need it later.

import axios from "axios";
//1. Secondary packaging of axios
const requests = axios.create({
    //Base path. The request sent by requests will be followed by baseURl after the port number
    baseURL:'/api',
    timeout: 5000,
})
//2. Configure request interceptor
requests.interceptors.request.use(config => {
    //config is mainly used to configure the request Header
    //For example, add a token
    
    return config;
})
//3. Configure corresponding interceptors
requests.interceptors.response.use((res) => {
    //Successful callback function
    return  res.data;
},(error) => {
    //Failed callback function
    console.log("Response failed"+error)
    return Promise.reject(new Error('fail'))
})
//4. External exposure
export default requests;

The front end solves cross domain problems through agents

Configure proxy in vue.config.js under the root directory to solve cross domain problems through proxy.
We have set the baseURL as api when encapsulating axios, so all requests will carry / api. Here we convert / api. If your project does not encapsulate axios or does not configure baseURL, it is recommended to configure it. To ensure that the baseURL is the same as the proxy mapping here, it is' / api 'here.

module.exports = {
    //Close eslint
    lintOnSave: false,
    devServer: {
        // True means hot update, false means manual refresh, and the default value is true
        inline: false,
        // development server port 8000
        port: 8001,
        //Proxy server solution cross domain
        proxy: {
            //The / api in the request path will be replaced by the following proxy server
            '/api': {
                //Provide the server address of the data
                target: 'http://39.98.123.211',

            }
        },
    }
}

Interpretation of relevant knowledge on webpack official website
webpack.config.js in the website is the vue.config.js file.

Unified encapsulation of request interface

Create an index.js file in the folder api to encapsulate all requests
Encapsulate each request into a function and expose it. The component only needs to call the corresponding function. In this way, when there are many interfaces, we only need to modify the file if necessary.

As follows:

//In the current module, the API is under unified management, that is, the request interface is under unified management
import requests from "@/api/request";

//Home page three-level classification interface
export const reqCateGoryList = () => {
    return  requests({
        url: '/product/getBaseCategoryList',
        method: 'GET'
    })
}

When a component wants to use related requests, it only needs to import related functions. The reqCateGoryList in the figure above is an example:

import {reqCateGoryList} from './api'
//Initiate request
reqCateGoryList();

nprogress progress bar

When opening a page, it is often accompanied by some requests, and a progress bar appears at the top of the page. Its principle is to open the progress bar when we initiate a request and close it after the request is successful, so we only need to configure it in request.js.
As shown in the figure below, we initiated a request when loading the page, and a blue progress bar appears at the top of the page

Corresponding request.js settings

import axios from "axios";
//Import progress bar
import nprogress from 'nprogress';
//Introducing progress bar styles
import "nprogress/nprogress.css";
//1. Secondary packaging of axios
const requests = axios.create({
    //Base path. The request sent by requests will be followed by baseURl after the port number
    baseURL:'/api',
    timeout: 5000,
})
//2. Configure request interceptor
requests.interceptors.request.use(config => {
    //config is mainly used to configure the request Header
    //For example, add a token

    //Open progress bar
    nprogress.start();
    return config;
})
//3. Configure corresponding interceptors
requests.interceptors.response.use((res) => {
    //Successful callback function

    //The response is successful. Close the progress bar
    nprogress.done()
    return  res.data;
},(error) => {
    //Failed callback function
    console.log("Response failed"+error)
    return Promise.reject(new Error('fail'))
})
//4. External exposure
export default requests;

You can modify the progress bar color by modifying the background of the nprogress.css file.

Manual introduction of vuex

First, ensure that vuex is installed, create a store folder in the root directory, and create index.js under the folder. The contents are as follows:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//An instance of an exposed store
export default new Vuex.Store({
    state:{},
    mutations:{},
    actions:{},
    
})

If you want to use vuex, you have to introduce it in main.js
main.js:
(1) Import file
(2) Register store
However, all entities registered in Vue instances in main.js will have the (this. $. Entity name) attribute in all components

import store from './store'
new Vue({
  render: h => h(App),
  //Register the route. At this time, the component will have the $route attribute
  router,
  //Register the store, and the component will have $store
  store
}).$mount('#app')

Tags: Javascript Vue Vue.js Webpack

Posted on Thu, 02 Dec 2021 22:07:01 -0500 by pytrin