Daily constant coding, lack of business summary, feel my growth is slow, just now, calm down to sum up some common vUE use tips

1. HookEvent is used to listen for life cycles in visual diagrams

The normal processing is to add a listener destruction event in the beforeDestroy lifecycle, but you can also listen to lifecycle functions via hooks. $on(‘hook:updated’, () => {}) $on(‘hook:updated’, () => {})

<template>
  <div class="echarts"></div>
</template>
<script>
export default {
  mounted() {
    this.chart = echarts.init(this.$el)
    // Listen for the window zoom event and call the relevant method:
    window.addEventListener('resize'.this.$_handleResizeChart)
    // The hook listener destroys the hook function and cancels the listener event
    this.$once('hook:beforeDestroy'.() = > {
      window.removeEventListener('resize'.this.$_handleResizeChart)
    })
  },
  updated() {},
  created() {},
  methods: {
    $_handleResizeChart() {
      this.chart.resize()
    }
  }
}
</script>
Copy the code

2. Click the list data to enter the parameter transfer question on the details page

Click on the commodity list page to enter the detailed interface of a commodity, and you need to upload a commodity ID. There are two methods of vue route parameter transmission: Query parameter transmission and Params dynamic route parameter transmission.

  1. Query Switches routes through path. Params switches routes by name
// query Switches routes through path
<router-link :to="{path: 'Detail', query: { id: 1 }}"> Go to the Detail page </router-link>// Params switches routes by name
<router-link :to="{name: 'Detail', params: { id: 1 }}">Go to the Detail page</router-link>
Copy the code
  1. Query bythis.$route.queryReceiving parameters; Params throughthis.$route.paramsReceive parameters
// query receives parameters through this.$route.query
created () {
    const id = this.$route.query.id;
}

// Params receives arguments via this.$route.params
created () {
    const id = this.$route.params.id;
}
Copy the code
  1. The url display of the passed parameter is different
Query The URL representation of the passed parameter: /detail? id=1&user=123&identity=1Params dynamic route url: /detail/123
Copy the code

It should be noted that params dynamic route parameters must be defined in the route, and then must be added when the route jumps. Such as:

// Only one id parameter is defined in the route
{
    path: 'detail/:id'.name: 'Detail'.components: Detail
}

// The parameter id and token are worn; Id is a parameter that has been defined in the route, whereas token is not
<router-link :to="{name: 'Detail', params: { id: 1, token: '123456' }}"> Go to the Detail page </router-link>// Receive on the details page
created () {
    // All of the following can be obtained normally, but after the page is refreshed, the ID can still be obtained, and the token does not exist
    const id = this.$route.params.id;
    const token = this.$route.params.token;
}
Copy the code

3. Vue. Observable can be used to replace Vuex for state management in small projects

Vuex is suitable for the development of large projects. Vuex can be replaced by Vue. Observable to create a simple Vuex state management. In fact, the core idea is the realization of observer mode in essence.

// Create the file store.js

import Vue from 'vue'
export const store = Vue.observable({
  userInfo: {},
  roleIds: []})// define mutations, which provides the function of modifying attributes:
export const mutations = {
  setUserInfo(userInfo) {
    store.userInfo = userInfo
  },
  setRoleIds(roleIds) {
    store.roleIds = roleIds
  }
}
Copy the code
// Reference the store.js file in the component

<template>
  <div>
    {{ userInfo.name }}
  </div>
</template>
<script>
import { store, mutations } from '.. /store'
export default {
  computed: {
    userInfo() {
      return store.userInfo
    }
  },
  created() {
    mutations.setUserInfo({
      name: 'zijun'}}})</script>
Copy the code

4. Application and encapsulation of AXIos

In SRC we create a request folder, create http.js and api.js files, and wrap our AXIos with http.js. Matches the default interface URL prefix with the Node environment variable. Axios.defaults. baseURL Sets the default request address for axios.

import axios from 'axios';
import router from '.. /router';
import {MessageBox, Message} from 'element-ui';
import store from '@/store/index';       // Introduce Vuex state management
// Environment selection
if (process.env.NODE_ENV == 'development') {    
    axios.defaults.baseURL = 'https://www.development.com';
} else if (process.env.NODE_ENV == 'production') {    
    axios.defaults.baseURL = 'https://www.production.com';
}
// Set request timeout:
axios.defaults.timeout = 10000;
// Set the post header:
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
Copy the code

Request interception — after login, the user’s token is stored locally through localStorage or cookie. Then when the user enters the page (i.e. in main.js), the user will first read the token from the localStorage. If the token exists, the user has logged in. Then update the token status in the VUEX. Then, each time you request an interface, you will carry a token in the header of the request, and the background staff can judge whether your login is expired according to the token you carry. If you do not carry the token, it indicates that you have not logged in.

axios.interceptors.request.use(    
    config= > {        
        const token = store.state.token;        
        token && (config.headers.Authorization = token);       // The token is inserted into the request header
        return config;    
    },    
    error= > {   
        Message.warning(error);
        return Promise.error(error);    
})
Copy the code

Response interception — that’s the data the server sends back to us that we can do something with before we get it. The Toast() method, which is the Toast light prompt component in the Vant library that I introduced.

axios.interceptors.response.use(    
    response= > {   
        if (response.status === 200) {            
            return Promise.resolve(response);        
        } else {            
            return Promise.reject(response); }},// Error status codes can expand themselves
    error= > {            
        if (error.response.status) {            
            switch (error.response.status) {                
                // 401: Not logged in
                case 401:                    
                    router.replace({                        
                        path: '/login'.query: { 
                            redirect: router.currentRoute.fullPath 
                        }
                    });
                    break;

                // 403 Token expired
                case 403:
                     Toast({
                        message: 'Login expired, please log in again'.duration: 1000.forbidClick: true
                    });
                    / / remove the token
                    localStorage.removeItem('token');
                    store.commit('loginSuccess'.null);
                    // Jump to the login page and upload the fullPath of the page to be accessed. After successful login, jump to the page to be accessed
                    setTimeout(() = > {                        
                        router.replace({                            
                            path: '/login'.query: { 
                                redirect: router.currentRoute.fullPath 
                            }                        
                        });                    
                    }, 1000);                    
                    break; 

                // 404 request does not exist
                case 404:
                    Toast({
                        message: 'Network request does not exist'.duration: 1500.forbidClick: true
                    });
                    break;
                // Other errors, directly throw error message
                default:
                    Toast({
                        message: error.response.data.message,
                        duration: 1500.forbidClick: true
                    });
            }
            return Promise.reject(error.response); }}});Copy the code

5. Timer cleaning problem — two implementation methods

  1. The usual action is to define a timer in the data function and destroy it beforeDestroy().
data() {            
    return {                              
        timer: null  // Timer name}}this.timer = (() = > {
    // Some operations
}, 1000)

// Destroy the timer
beforeDestroy() {
    clearInterval(this.timer);        
    this.timer = null;
}
Copy the code
  1. The timer is cleared by the position of the $once event listener after the timer is defined
const timer = setInterval(() = >{                    
    // Some timer operations
}, 500);  

// Listen on timer with $once, the beforeDestroy hook can be cleared.
this.$once('hook:beforeDestroy'.() = > {            
    clearInterval(timer);                                    
})
Copy the code