[Vue technology stack development foundation guide]

Vue front end development framework

Vue cli project scaffold is based on Vue JS for rapid development of a complete system
Document address https://cli.vuejs.org/zh/
  1. Install node js https://nodejs.org/zh-cn/
  2. Install Vue cli scaffold
npm install -g @vue/cli

  1. Create a vue project
Execute command vue create hello-world(Project name) Quickly create a vue project

1) After executing the command, you will be prompted to select what kind of preconfiguration we choose Manually select features Manually select configuration
2) Check the features needed for your project Check the required element in the space
     (*) Choose Vue version  // Select vue version
     (*) Babel // javascript syntax compiler
     ( ) TypeScript
     ( ) Progressive Web App (PWA) Support
     (*) Router // Vue router routing manager
     (*) Vuex  // Status manager
    >(*) CSS Pre-processors // Select CSS preprocessor
     (*) Linter / Formatter // Select formatting and validation rules
     ( ) Unit Testing

  1. Start the project, run the command on the terminal, and check the package Define the command in the scripts of the JSON file, and then use npm run 'command name' to execute
    For example: NPM run serve, NPM run build, NPM run serve: prod
{
  "name": "trechkpcadminview",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "serve:prod": "vue-cli-service serve --mode production",
    "lint": "vue-cli-service lint"
  },
  ...

  1. Project mode and environment variables

    pattern

    Pattern is an important concept in Vue CLI project

    • -By default, a Vue CLI project has three modes

    • The development mode is used for Vue client service

      development
    • The test mode is used for Vue cli service test: unit

      The test pattern creates an optimized webpack configuration designed for unit testing. It does not handle images and other resources that are not necessary for unit testing
    • production mode is used for Vue cli service build

      The production mode creates a optimized webpack configuration for use in the production environment
    • You can override the default mode for the command line by passing the -- mode option parameter. For example, if you want to use development environment variables in build commands

    vue-cli-service build --mode development
    // When running the Vue cli service command, all environment variables are loaded from the corresponding environment file
    
    environment variable

    You can specify environment variables by placing the following files in your project root directory:

    // This is the environment file
    .env                # Loaded in all environments
    .env.local          # It is loaded in all environments, but it will be ignored by git
    .env.[mode]         # Is loaded only in the specified mode
    .env.[mode].local   # It is only loaded in the specified mode, but it will be ignored by git
    

    The environment variable specified in the environment file is in the form of key=value. If the environment file does not contain NODE_ENV is a variable whose value depends on the mode. For example, it is set to "production" in production mode and "test" in test mode. The default is "development".

    NODE_ENV will determine the running mode of your application, whether it is development, production or test, so it also determines what kind of webpack configuration to create.

    An environment file contains only "key = value" pairs of environment variables:

    FOO=bar
    VUE_APP_NOT_SECRET_CODE=some_value
    
    // Only NODE_ENV,BASE_URL and VUE_APP_  The first variable will be passed through webpack Defineplugin is statically embedded in the code on the client side
    
    // You can access them this way in your application's code
    console.log(process.env.VUE_APP_SECRET)
    
Vue router official routing manager
Document address: https://router.vuejs.org/zh/

By combining components to form an application, all we have to do is map components to routes, and then tell Vue Router where to render them

// 1. Define (route) components.
// You can import from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

const Menu= ()=>import(/* webpackChunkName: "basic" */ '@/views/basic/menu')

// 2. Define route
// Each route should map a component. Where "component" can be
// Via Vue The component constructor created by extend(),
// Or, just a component configuration object.

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar },
  { path: '/menu', component: Menu },
]

// 3. Create a router instance and then transfer it to 'routes' configuration
const router = new VueRouter({
  routes // (abbreviation) equivalent to routes: routes
})

// 4. Create and mount root instances.
// Remember to inject routes through router configuration parameters,
// So that the whole application has routing function
const app = new Vue({
  router
}).$mount('#app')
  1. Create a Router instance
let router=new VueRouter({
  routes: [
    // Dynamic path parameters start with a colon
    { path: '/user/:id', component: User }
  ]
})
// router is an instance object. There are many APIs of instance objects that can be called to consult documents
  1. Common examples and methods of Router
// Instance method of route jump
router.push(location, onComplete?, onAbort?)
router.push(location).then(onComplete).catch(onAbort)
router.replace(location, onComplete?, onAbort?)
router.replace(location).then(onComplete).catch(onAbort)
router.go(n)
router.back()
router.forward()

  1. Global navigation guard for routing
router.beforeEach((to, from, next) => {  // The front guard executes before the route enters 
  /* Must call ` next` */
})

router.afterEach((to, from) => {}) // The post guard executes after the route enters
  1. Routing guard within component

    • beforeRouteEnter
    • beforeRouteUpdate
    • beforeRouteLeave
  2. Common routing object properties

    $route.path // The path of the current route
    $route.params // A key/value object with routing parameters is an empty object
    $route.query // A key/value object that represents the URL query parameter for the path / foo? If user = 1, $route query. User = = 1. If there is no query parameter, it is an empty object
    $route.fullPath // The URL after parsing, including the full path of query parameters and hash
    $route.matched // An array containing the route records of all nested path segments of the current route
    ...

  1. HTML5 History mode

    The default hash mode of Vue router uses the hash of the URL to simulate a complete URL, so when the URL changes, the page will not be reloaded.

    If we don't want ugly hash, we can use the history mode of routing, which makes full use of history Pushstate API to complete URL jump without reloading the page.

    However, to play this mode well, it also needs background configuration support. Add a candidate resource covering all situations on the server: if the URL does not match any static resources, the same index should be returned HTML page

Vue core plug-in vuex status management plug-in
Document address: https://vuex.vuejs.org/zh/

Vuex is designed for Vue State management mode of JS application development

It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.

Vuex is also integrated into Vue's official debugging tool devtools extension (opens new window), which provides advanced debugging functions such as time travel debugging with zero configuration, import and export of state snapshots and so on

Vuex can help us manage shared state, with more concepts and frameworks
If you don't plan to develop large single page applications, using Vuex can be cumbersome and redundant

State

Vuex uses a single state tree and contains all application level states with one object
state acts as a "unique data source"

Getters

Just like calculating attributes, the return value of getter will be cached according to its dependency, and will be recalculated only when its dependency value changes

Mutations

The only way to change the state in Vuex's store is to submit the mutation

The mutation in Vuex is very similar to an event:
Each mutation has a string event type and a callback function. This callback function is where we actually change the state, and it will accept state as the first parameter

Actions

Action is similar to mutation in that:

  • The Action submits the mutation instead of directly changing the status.
  • An Action can contain any asynchronous Action.
Actually used in the project
  1. Install npm install vuex
  2. Index. In the store folder JS introduces vue and vuex
// src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
  1. Create the store object of vuex and set the core object state, getters, variations and actions
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

export default store
  1. Inject the store object of vuex into the vue instance object
import store from './store'

new Vue({
  router,
  store, //
  render: h => h(App)
}).$mount('#app')
Axios is a promise based HTTP library

axios is supported by relying on the native implementation of ES6 Promise

Document address: https://www.kancloud.cn/yunye/axios/234845
  • Promise API supported
  • Intercept requests and responses
  • Convert request data and response data
1. Create an instance
// The create method of axios returns an axios instance
var service = axios.create({
  baseURL: 'https://pd.t-rech.com/reception',
  timeout: 10000,
  
  ...
});
2. Example method
request(config)
get(url[, config])
delete(url[, config])
head(url[, config])
post(url[, data[, config]])
put(url[, data[, config]])
patch(url[, data[, config]])

3. Common request configuration of Axios
// config common configuration references are as follows

{
  // `URL ` is the server URL for the request
  url: '/user',

  // `Method ` is the method used when creating the request
  method: 'get', // The default is get

  // `baseURL 'will be automatically added before' URL ', unless' URL' is an absolute URL.
  // It can set a 'baseURL' to facilitate the delivery of relative URL s for axios instance methods
  baseURL: 'https://some-domain.com/api/',

  // `headers ` is the custom request header to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params ` is the URL parameter to be sent with the request
  params: {
    ID: 12345
  },
  data: {
    firstName: 'Fred'
  },

  // `Timeout ` specifies the number of milliseconds the request times out (0 means no timeout)
  // If the call cost exceeds the 'timeout', the request will be interrupted
  timeout: 1000,

  ...

}
4. Response structure
{
  // `data ` response provided by the server
  data: {},

  // `Status ` HTTP status code from the server response
  status: 200,

  // `statusText ` HTTP status information from the server response
  statusText: 'OK',

  // `headers ` the header of the server response
  headers: {},

  // `config ` is the configuration information provided for the request
  config: {}
}
5. Customize axios instances and set global default values
// Set the default value of the configuration when creating an instance
var service = axios.create({
  baseURL: 'https://pd.t-rech.com/reception',
  timeout: 10000,
  
  ...
});
perhaps service.defaults.baseURL = 'https://pd.t-rech.com/reception; 
6. Interceptor
request interceptor
// Add request interceptor
service.interceptors.request.use(function (config) {
    // What to do before sending the request
    return config;
}, function (error) {
    // What to do about request errors
    return Promise.reject(error);
});

In the actual combat of the project, the request interceptor often configures the existing token into the request header to set the unified token request header, for example:

service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
Response interceptor
// Add response interceptor
service.interceptors.request.use(function (response) {
    // Do something about the response data
    return response;
}, function (error) {
    // Do something about response errors
    return Promise.reject(error);
});

  1. In the actual combat of the project, the response interceptor is commonly used to get the token in the response header in the interface and update the previously saved token.
  2. Process the returned data, carry out unified data packaging, and standardize the data format returned by the interface
    For example:
service.interceptors.response.use(

  response => {
    const { authorization } = response.headers
    if (authorization) {
      setToken(authorization)
    }
    const res = response.data

    if (res.code !== 'S_00001') {
      // E_30019 E_30011 session failure
      if (res.code === 'E_30019' || res.code === 'E_30011') {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      Message({
        showClose: true,
        type: 'error',
        message: res.msg
      })

      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message || 'Request error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

Keywords: Javascript Front-end Vue.js

Added by Ryanz on Mon, 14 Feb 2022 11:38:58 +0200