Development skills

Encapsulation axios

import axios from 'axios'
const instance = axios.create({
	timeout: 1000 * 5
})

Copy the code

Automatically import the module file require.context()

For example,

Automatically import module files in store

  • The directory structure
├ ─ store │ │ index. Js │ │ │ └ ─ modules │ attribute. Js │ brand. Js │ category. Js │ goods. Js │ home. Js │ login. Js │ order. Js │ topic. Js └ ─ viewsCopy the code
  • The key code
// store/index.js
// ...

// Automatically import modules
const modulesFiles = require.context('./modules'.false./\.js$/)

'import app from './modules/app'
// It automatically imports /\.js$/ regular-expression files from './modules'
const modules = modulesFiles.keys().reduce((modules, modulePath) = > {
  // put './user.js' => 'user'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/.'$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})
// ...

export default new Vuex.Store({
  modules,  // modules: modules,
  // ...
})
Copy the code

Learn more about

Globally register multiple filters

  • src/filters/index.jsdirectory
// Define the filter

export function filter1 (time) {
  // todo ...
},
export function filter2 (time) {
  // todo ...
},
export function filter3 (time) {
  // todo ...
},
// ...
Copy the code
  • In the main. Js
/ / introduction
import * as filters from './filters' / / the global filters

/ / register
Object.keys(filters).forEach(key= > {
  Vue.filter(key, filters[key])
})
Copy the code
  • Used in xxx.vue
<! - a single - > < p > price: {{count | filter1}} < / p > <! More than -- -- -- > < p > price: {{count | filter1 | filter2 | filter3 |... }}</p>Copy the code

Hook use

@hook: Created, Mounted…

Listen for the subcomponent declaration cycle

// In the parent component
<Child @hook:mounted="todoFn"/>
...
methods: {
    todoFn() {
      console.log("Trigger child component Mounted"); }},Copy the code

Replace file names to introduce file paths such as @ instead of SRC (alias to introduce smart hints)

  • Create a new one in the project directoryjsconfig.json
{
  "compilerOptions": {
    "baseUrl": ". /"."paths": {
         / / alias
          "@ / *": ["src/*"]."@com/*": ["src/components/*"]."@views/*": ["src/views/*"]."@css/*": ["src/styles/*"]."@img/*": ["src/assets/images/*"]."@js/*": ["src/utils/*"],}},"exclude": ["node_modules"."dist"]  / / out
}
Copy the code
  • invue.config.js
/ / = = = = = = = = = = = = = = = = = = = = = = configure an alias start = = = = = = = = = = = = = = = = = = = = = = = = = =
const path = require('path')
function resolve(dir) {
    return path.join(__dirname, dir)
}

module.exports = {
    // Alias configuration
    chainWebpack: (config) = > { 
        config.resolve.alias
            .set(The '@', resolve('src'))
            .set('@com', resolve('src/components'))
            .set('@views', resolve('src/views'))
            .set('@css', resolve('src/styles'))
            .set('@img', resolve('src/assets/images'))
            .set('@js', resolve('src/utils'))
            // ...
    },
    
    / / or
   /* configureWebpack: {resolve: {alias: {'@': resolve(' SRC '), '@com': resolve(' SRC /components'), }}}, * /
    / / = = = = = = = = = = = = = = = = = = = = = = configure an alias end = = = = = = = = = = = = = = = = = = = = = = = = = =
    
    productionSourceMap: false.// Unpack the image file
  	devServer: {// port:' port '
        open:true.// The project is automatically opened in the default browser upon successful startup
        hot:true,},// ...
}
Copy the code
  • Installation path prompts plug-inPath Intellisense.Re-open the project with vscode(If the above two steps succeed, skip this step)
  • Use the sample

Js – cookies operation cookies

  • The installation
NPM I js-cookie-s or YARN add js-cookieCopy the code
  • Self-encapsulation
import Cookies from 'js-cookie'
const TokenKey = 'token'

// set cookies
export function setToken(token) {
    return Cookies.set(TokenKey, token)
}

// get cookies
export function getToken() {
    return Cookies.get(TokenKey)
}

// remove cookies
export function removeToken() {
    return Cookies.remove(TokenKey)
}
Copy the code
  • use
/ / introduction
import { setToken, getToken, removeToken } from '@/utils/auth'

/ / use
setToken(res.data.token)   // Others look at the encapsulated code to pass arguments
Copy the code
  • Js – cookie making address

Enter the login

mounted() {
    // Bind the carriage return event
    document.addEventListener("keydown".this.keyDown, false);
  },
  destroyed() {
    // Destruction event
    document.removeEventListener("keydown".this.keyDown, false);
  },
  methods: {
    // Keyboard events
    keyDown(e) {
      e = window.event || e;
      if (
        this.$route.path == "/login" &&
        (e.code == "Enter" || e.code == "enter")) {Verify that in the login screen and press enter
        this.handleLogin("loginForm"); // The login function}}},Copy the code

Filter reuse

  • It can be used not only in templates, but also in component instances
  • Both local and global are accessible
filters: {
    formMoney(val) {
      return Number(val).toFixed(2); }},// The filters are the same as properties, methods, as follows
computed: {getNum(){
      return this.$options.filters.formMoney(20)}}Copy the code

.sync modifies custom properties passed by the parent component (simplifies child to parent code)

/ / the parent component
<Child :title.sync="title"></Child>

/ / child component
<p @click="$emit('update:title', 'hello')">{{ title }}</p>
props: {
    title: {
      type: String.default: "",}},Copy the code

Render function using

scenario

<template>
  <div>
    <div v-if="level === 1"> <slot></slot> </div>
    <p v-else-if="level === 2"> <slot></slot> </p>
    <h1 v-else-if="level === 3"> <slot></slot> </h1>
    <h2 v-else-if="level === 4"> <slot></slot> </h2>
    <strong v-else-if="level === 5"> <slot></slot> </stong>
    <textarea v-else-if="level === 6"> <slot></slot> </textarea>
  </div>
</template>
Copy the code

To optimize the

<template> <div> <child :level="level">Hello world! </child> </div> </template> <script> import Vue from 'vue' Vue.component('child', { render(h) { const tag = ['div', 'p', 'strong', 'h1', 'h2', 'textarea'][this.level-1] return h(tag, this.$slots.default) }, props: { level: { type: Number, required: true } } }) export default { name: 'hehe', data() { return { level: 3 } } } </script>Copy the code
  • reference

Use of the LoDash library

Lodash website

The installation

npm i -S lodash
Copy the code

use

var _ = require('lodash');
Copy the code

Commonly used method

  • Image stabilization
_.debounce(func, [wait=0], [options={}])
Copy the code
  • The throttle
_.throttle(func, [wait=0], [options={}])
Copy the code