Technology is introduced

  • Vuejs: Core VUE

  • Vuex: state management plug-in

  • Vue-router: indicates a routing plug-in

  • Axios: Ajax request

  • Json-bigint: indicates the maximum security value processing

  • Socket. IO -client: instant messaging library

  • Vant: Move component libraries

  • Amfe-flexible: REM flexible

  • Vue-lazyload: lazy loading of images

  • Package App: DCLOUD package

I. Project creation

steps

Create a project

Vue create Project name

Choose a custom way to create the project

? Please pick a preset: (Use arrow keys)
  wzr ([Vue 2] less, babel, router, eslint)
  wz ([Vue 2] less, babel, router, vuex, eslint)
  Default ([Vue 2] babel, eslint)
  Default (Vue 3) ([Vue 3] babel, eslint)
> Manually select features
Copy the code

Manual selection feature

? Check the features needed for your project:
 (*) Choose Vue version
 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 (*) Router
>(*) Vuex
 (*) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing
Copy the code

version

? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
> 2.x
  3.x
Copy the code

Is the history mode used for routing?

? Use history mode for router? (Requires proper server setup forindex 
fallback in production) (Y/n) n
Copy the code

CSS preprocessor

? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are 
  supported by default): (Use arrow keys)
  Sass/SCSS (with dart-sass)
  Sass/SCSS (with node-sass)
> Less
  Stylus
Copy the code

Code style.

? Pick a linter / formatter config:
  ESLint with error prevention only
  ESLint + Airbnb config
> ESLint + Standard config
  ESLint + Prettier
Copy the code

Check the node

? Pick additional lint features:
 (*) Lint on save
>(*) Lint and fix on commit
Copy the code

Stores the plug-in configuration location

? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files
  In package.json
Copy the code

Whether to save the previous Settings as the default scheme

? Save this as a preset for future projects? (y/N) n
Copy the code

If the default name scheme is no longer needed, you can delete the.vuerc file under C:\Users\ username

Creating a successful

πŸŽ‰  Successfully created project vuex_day3.
πŸ‘‰  Get started with$CD vuex_day3 (enter project) $NPM run serve (start project)Copy the code

Create a remote repository

Log on to Gitee and set up an empty warehouse with the same name as the local project.

  • Same name as local project. This simplifies push commands.

  • An empty warehouse. That is, do not have any files in the remote warehouse, convenient to directly push up.

Once created, you should see the following page

Git git git git git git git git git git git

  • Add the remote warehouse address to the local warehouse

    Git remote add Origin Specifies the remote repository address

  • Push to remote repository

    git push -u origin master

If there are subsequent code changes that need to be committed to a remote repository, two steps are required:

Git add. Git commit -mCopy the code
  • After the first push (git push -u origin master), you just need to write git push

Common Mistakes

  • Problem 1: Unable to push to Gitee. (Observe the error message)

    Possible cause: Incorrect password/user name (if git push fails, you must check carefully)

    Solution: Delete the local credentials and re-enter the user name and password.

Once deleted, git push will pop up again asking you to rewrite your username and password.

  • Fault 2: Gitee git remote add Origin fails

    Example graph of error:

Solution:

Git remote remove origin 2. Add git remote add Origin XXXXXXX againCopy the code
  • Problem 3: After the project is created, the Git log does not commit records, causing git push to fail.

    Git is not installed

    Solution: Install Git

Working directory

β”œβ”€ β”œβ”€ public # β”œβ”€ favicon. Ico β”‚ β”œβ”€ SRC β”œβ”€ API # β”œβ”€ assets # Resource directory β”œ ─ ─ components # components directory β”œ ─ ─ the router # routing module β”œ ─ ─ store # Vuex container module β”œ ─ ─ styles # style directory β”œ ─ ─ utils # tool module directory β”œ ─ ─ views # View components directory β”” ─ ─ home # homepage module | β”œ ─ ─ home. Vue β”œ ─ video # video module | β”œ ─ ─ video. Vue β”œ ─ question # quiz module | β”œ ─ ─ question. Vue β”œ ─ search # search module | β”œ ─ ─ search. Vue β”œ ─ user # user module | β”œ ─ ─ the user. The vue β”” ─ Layout. The vue # common Layout components β”œ ─ ─ App. Vue # root component β”” ─ ─ the main, js # entry documents β”œ ─ ─ .browserslistrc # Browser's contract β”œβ”€.EditorConfig # Editor's contract to use in this project β”œβ”€.eslintrc.js # esLint Configures β”œβ”€.gitignore # gitignore Settings, β”œβ”€ β”œβ”€ package.json # β”œβ”€ download.txt β”œβ”€ download.txt # download.txt β”œβ”€ download.txt # download.txt # download.txt Project description documentCopy the code

3. Custom changes

The default generated directory structure does not meet our development needs, so we need to make some custom changes here. There are two main jobs:

  • Delete the initialized default file
  • Added tweaks to the directory structure we need

delete

  1. Clear the contents in SRC /views/ app. vue.

Note that ESLint requires that the last line of each file be left blank ==

  1. Delete files generated by default:
  • components/HelloWorld.vue
  • views/Home.vue
  • views/About.vue

new

Add the following directories to the SRC directory:

  • / API: stores the request function module
  • /styles: styles file module
  • /utils: utility function module

Vant component library

Vue. Js Mobile component library

There are many mobile component libraries based on vue.js, and some are recommended in the official awesome:

– Mint UI: Am I hungry (Element-UI mobile version)

-Vant: Yizan

– Cube-UI: Didi

-Nutui: JD Company

The Vant (address on the code cloud) is used in our project.

1. Install

NPM install vant –save

NPM I xxx-d /–save-dev: NPM I xxx-d /–save-dev: NPM I xxx-d /–save-dev

2. Introduce the Vant component library

There are two ways to use the Vant component library in a VUE project:

A complete introduction

Benefits: Easy to use (you don’t need to import components every time you use them)

Disadvantages: large packing volume

According to the need to introduce

Benefits: Small package size

Cons: slightly more cumbersome than importing all: import components every time you use them

Conclusion: Use the full introduction approach directly when developing the project, and adjust it when the project is packaged

Specific code:

The Vant component is fully introduced as a vUE plug-in in SRC /main.js

import Vue from 'vue'
import Vant from 'vant' / / component library
import 'vant/lib/index.css' / / style

Vue.use(Vant) / / introduction
Copy the code

Use 3.

In app.vue (any other component will do), test use

<van-button type="default"> Default button </van-button><van-button type="primary">The main button</van-button>
<van-button type="info">Information button</van-button>
<van-button type="warning">The warning button</van-button>
<van-button type="danger">Dangerous button</van-button>
Copy the code

Van-button is a button component provided in the Vant component library

Results the following

ESLint- Basic introduction

ESLint is a code checker that checks whether your code conforms to specified specifications (e.g. = must have a space before and after it)

  • specification
    • Industry-recommended specifications; When creating the project, we use JavaScript ==Standard== Style code Style rules
    • Custom specifications. You and your team can agree on your own set of norms
  • The advantage of using ESLint is that the code style is uniform when multiple people collaborate

Eslint is the judge, Standard is the law

The vue-CLI tool provides an option when creating a project, which we selected earlier when creating the project, so it takes effect directly in this project

JavaScript Standard Style specifications

github.com/standard/st…

If you cannot find the rules Look at here: www.verydoc.net/eslint/0000…

Four ways to correct mistakes

There are four ways to correct errors:

  • Manual correction: Human modification
  • Command modification: NPM run lint
  • Modify the rules: make the code conform to the modified rules so that no errors are reported
  • Plugin fix: works with the eslint plugin in vscode

1. Manually correct

Follow the error prompts to manually correct item by item.

If you don’t know what the syntax on the command line means, you can use the error rule names (fun-call-spacing, space-in-parens,…..) Go to the ESLint rule list website to find the exact meaning.

2. Modify the command

Vuecli provides automatic repair when creating a project (some complex errors still need to be corrected manually) by running:

npm run lint

3. Modify rules (ESLint- Custom rules)

Under the root of the project, there is a.eslintrc.js file that configates ESLint with a property that sets custom code rules: rules

module.exports = {
  root: true.// The current project uses this configuration file and does not look for.eslintrc.js files in the parent directory
  env: { // Specify the esLint startup environment (vuecli is underlying node support), browser: true can also be set in the browser
    node: true
  },
  extends: [ // Extend the configuration
    'plugin:vue/essential'.// Mandatory rules in vUE
    '@vue/standard' // make esLint inherit the -standard from @vue/cli scaffolding].parserOptions: { // Use eslint for new syntax
    parser: 'babel-eslint' // Use babel-eslint to parse the new syntax ES6
  },
  // You can configure custom rules here
  // key: rule code
  // value: specifies the qualification mode
  // "off" or 0 - Disables the rule
  // "warn" or 1 - Treats the rule as a warning (does not affect the exit code), only warns, does not exit the program
  // "error" or 2 - Treat the rule as an error (exit code 1), report an error and exit the program
  // Custom rules - There are many built-in rules that can be modified here
  rules: {
     // The live environment prints a warning, and the development environment disables this rule
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.// The debugger can terminate code execution
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.// No consecutive blank lines allowed (off rule)
    'no-multiple-empty-lines': 'off'}}Copy the code

Rules is an object that conventions rules in the form of key-value pairs:

  • The key name is the rule name (available in error messages and on esLint’s website)
  • Values are the specifications for this rule, most commonly off, WARN, and error.

4. Plugin fixes

When opening a project with vscode, use the scaffold project as the vscode root, since eslint uses the configuration file.eslintrc

Five steps:

Supplementary content:

{
  "eslint.enable": true."eslint.run": "onType"."eslint.options": {
      "extensions": [
          ".js".".vue".".jsx".".tsx"]},"editor.codeActionsOnSave": {
      "source.fixAll.eslint": true}}Copy the code

More rules: www.cnblogs.com/jiaoshou/p/…

Possible problems

1. CTRL + S Does not format automatically

Open a code file with ESLint in the bottom right corner. If so, click and select AnyWhere to effect AnyWhere in the pop-up dialog box.

“V” means on

2. Auto indent

  • Uninstall the Beautify plugin – esLint also beautifies code

  • There may also be JS/CSS Format plug-ins/other beautification plug-ins ==

    Do not want to uninstall can be disabled

  • If you enable automatic formatting in vscode with other extensions, you may run afoul of eslint’s rules!

    Turn off automatic formatting in vscode

  • If this does not work, change the configuration of vscode

    File > Settings, search for this and uncheck the box below

3. Save, single citation change double citation

The vetur plugin conflicts with ESLint. Modify the ESLint plugin configuration to override this code

{
    "eslint.run": "onType"."editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "vetur.validation.template": false.// Remove the template from the vetur extension
	"editor.formatOnSave": false.// get rid of vscode autosave, vscode is false by default, if you want to use eslint formatting, the default formatting will not be enabled
    "eslint.enable": true.// eslint formats the configuration
    "eslint.autoFixOnSave": true.// esLint automatically resolves syntax errors when saved
    "eslint.options": { // ESLint option - formats JS and vue files
        "extensions": [
            ".js".".vue"]},"eslint.validate": [
        "javascript",
        {
            "language": "vue"."autoFix": true,},"html"."vue"],}Copy the code

Use REM to solve multi-screen adaptation

Use REM adaptation technology

Since this project is a mobile project (users access it through mobile phones), it needs to be adapted to different mobile screens

Styles in Vant use PX units by default. If you need rem units, it is recommended that you use the following two tools together to achieve this goal. Official website address]()

  1. Change all px units to REM, using PostCSs-pxtoREM, which is a PostCSS plugin for converting PX to REM.

  2. Rem reference values are dynamically set according to the width of the phone screen: font size on the HTML tag. Use lib-flexible to set rem reference values.

  • The corresponding package name is not that, but amFE-Flexible.
  • It needs to be production dependent

1. The installation package

The difference between:

Use # -d to indicate dependencies during post-processor development. This package will not be needed once the project is live (just use px-> REM during development). NPM I [email protected] -d # Change rem reference value js plugin needs to be used after package # function: The rem value is adjusted according to the screen width. The default is 1/10 of the screen width. The default is 37.5npm I amfeflexibleCopy the code

2. Set the postcss

Create the postcss.config.js file

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      // Convert px units of all elements to Rem
      // rootValue: Convert the base value of px.
      // For example, if an element is 75px wide, then it is 2rem.
      rootValue: 37.5.propList: [The '*']}}}Copy the code

Once this is done, restart the project with NPM Run Serve, which will automatically convert the px units in the original style to REM units

3. The introduction of flexible

Import amfe-flexible in the import file SRC /main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// Import all Vant components
import Vant from 'vant'
// Use its style
import 'vant/lib/index.css'

// It adjusts rem reference values based on the phone's size: font size on the HTML tag.
import 'amfe-flexible'
Copy the code

7. Axios – Encapsulates the axios request tool

To make ajax calls easier, we’ll wrap AXIos into a separate module that can be loaded and used as needed

1. Install axios

Install AXIOS into the project

npm i axios

2. Secondary encapsulation

Create the SRC /utils/request.js file

// Encapsulate axios twice
// Axios itself is a stand-alone library that wraps around Ajax. We repackage it for easy use in the project
// (1) Interface base address
// (2) request, response interceptor

import axios from 'axios'

const instance1 = axios.create({
  // Back-end server 1
  baseURL: ' ' // The interface address of the project line
})

const instance2 = axios.create({
  // Back-end server 2
  baseURL: ' '
  // timeout: 1000,
  // headers: {'X-Custom-Header': 'foobar'}
})

export { instance1, instance2 }

Intance1 is exported by default
export default instance1
Copy the code

BaseURL is a keyword and cannot be misspelled

Understand multiple base addresses

3. The test

<template>
  <div id="app">
    <van-button type="primary" @click="hTestAxios2">Test axios effect -async</van-button>
    <router-view/>
  </div>
</template>
<script>
import { instance2 } from '@/utils/request.js'
// import request from '@/utils/request.js'
export default {
  methods: {
    hTestAxios1 () {
      instance2({
        method: 'GET'.url: 'v1_0/user/channels'
      }).then(res= > {
        console.log(res)
      }).catch(err= > {
        console.log(err)
      })
    }
  }
}
</script>
Copy the code

You can see something like this in the console:

Axios – review the async – await

1. The content

async hTestAxios2 () {
  try {
    const res = await instance2({
      method: 'GET'.url: 'v1_0/user/channels'
    })
    console.log(res)
  } catch (err) {
    console.log(err)
  }
}
Copy the code

2. try-catch

If something goes wrong in the try, it goes into the catch.

This is a little bit of a mistake. Maybe the Ajax operation is not wrong, but the subsequent operation is wrong, and we will mislead the error to Ajax.

async hTestAxios2 () {
      try {
        const res = await instance2({
          method: 'GET'.url: 'v1_0/user/channels'
        })
        console.log(res.data.data.adc.length) // This sentence is wrong
      } catch (err) {
        console.log(err)
      }
    },
Copy the code

Axios – Encapsulates the business request module

1. Analyze problems with existing code

Unfriendly code

try {
  await ajax({
  	method: 'GET'.url: '/v1_0/user/channels'})}Copy the code

The ajax request in the above code is straightforward: click a button to make a request that writes out the URL, method, and parameters. But there are some problems with it doing so:

  • Not semantic enough (just know that you are making a request, not exactly what you are doing)
  • Inconvenient code reuse. If you need the channel information function in another module, you need to write it again.
  • The URL address cannot be changed uniformly. If you want to change the URL address, you need to look inside the component to locate it.

solution

Encapsulate all operations related to a business as a module in advance

2. Further encapsulate the business code

2.1 Building modules

Create API /channel.js and write

// Encapsulates all operations related to user operations
1. Log in, log out, change the password, and change the profile picture.....
import ajax from '.. /utils/request'
/** * User login *@param {*} Mobile Phone number *@param {*} Code password * /
export const getChannels = () = > {
  return ajax({
    url: '/v1_0/user/channels'.method: 'GET'})}Copy the code

2.2 Using Modules

To load the call on a specific page, there are two steps:

(1) Import the above package API

(2) call

// 1. Import the package API
import { getChannels } from '@/api/channel.js'


async hTestAxios2 () {
  try {
    / / 2. Call
    const res = await getChannels()
    console.log(res)
  } catch (err) {
    console.log(err)
  }
Copy the code

Then all requests for interfaces in the project should not be written directly to the component, but instead:

  • Let’s write the methods in the module. In the SRC/API/XXXX module

  • Then take the methods out of the module and use them in the component.

3. Possible problems

Remember to write return, otherwise you can’t get the result

export const getChannels = () = > {
  // request() θΏ™δΈͺε‡½ζ•°ηš„θΏ”ε›žε€Όζ˜―δΈ€δΈͺpromise
  return request({
    url: 'v1_0/user/channels'.method: 'GET'})}Copy the code

summary