preface

The summary is based on VUe2. X, VUE-cli3. x, mainly records some common vUE instructions, events, monitoring, data binding, filter, components, animation, vuex, VUe-Router and other things often used in daily work, but also some common plug-in and development tools introduction and use. As well as part of the performance optimization suggestions and practice, if there is wrong, or insufficient place, please also pointed out, learn to learn.

A basis,

1. Understand MVVM

  • M is data in vue instance, custom data or array returned by back end, not model concept in back end MVC.
  • Vm is the scheduler between VUE instances M and V is the core idea of MVVM
  • V is what the HTML will render

2. Common instructions

  • V-cloak solves {{}} interpolation flicker problem

  • V-text overwrites the original content of the element first, but interpolation only overwrites its own placeholders and does not blink by default

  • V-html renders HTML tags, overwriting the original content of elements

  • V-bind: to bind data, you can write valid JS expressions

  • V-on, short for @, is used to click events

3. Common event modifiers

  • Stop to prevent bubbling: There are methods on both the outer and inner layers. Clicking will cause bubbling and trigger events on the outer layer. The sequence produces events from the inside out

  • Prevent organizes the browser default behavior: the A TAB has the browser default behavior

  • Capture capture events: Click on the inner layer to trigger the outer layer and then trigger the inner layer. Events are generated from the outer layer to the inner layer

  • Self only triggers its own time and does not generate bubble and capture events. Similar to preventing bubble, but only for its own layer, the outer layer will still be bubbled up by the inner layer. Stop stops all layers

  • The once event is executed only once

4. Data binding

  • V-bind: one-way data binding

  • V-model: Two-way binding of data, which can only be used in form elements

Tips: Form elements: Radio, text, Address, email, SELECT, checkbox, TextaREA

5. Class binding

  • 1. Arrays with objects

    data(){ return{ flag:true } }

It is possible to write ternary expressions in more arrays, but it is recommended to use objects instead to control rendering

  • 2. Simple objects

    data(){ return{ falg1:true, falg2:true } }

  • 3. Array with ternary

    data(){ return{ falg:true, } }

  • 4. Upgrade the object

    data(){ return{ classObj:{classA:falg1,classB:flag2} } }

Tips: Use an array of objects directly to control styles

  • 5. Use the style object to change the style

    <div :class="styleObj" />
    
    data(){
        return{
          styleObj:{color:red}
        }
    }
    Copy the code
  • 6. Use style arrays with objects to implement style changes

    data(){ return{ styleObj1:{color:red}, styleObj2:{color:red} } }

6. Use of V-for

You can iterate over: ordinary arrays, object arrays, objects, and numbers

<div v-for='(item,key,index) in object' :key='index'>
 {{item}}--{{key}}--{{index}} 
</div>
<div v-for='(count in 10)'> </div>
Copy the code

** There are multiple indexes when iterating through objects, starting with 1 when iterating through numbers. To bind a key, the property value must be either number or string

7, V-if, V-show

  • V-if has high switching performance and fits elements that may never be seen by the user

  • V-show has a high initial rendering cost and is suitable for frequent switching of elements

Debug plug-ins

  • Look for the Vue-devTools plugin in the Google Store, use the plugin, and set up the plugin to allow access to file addresses. Vue related things will appear in debugging
  • The debugger can be debugged directly

9. Filter

Global and private filters

<div v-for='(item,key) in object' :key='index'>
 {{item | dateFormat}}
</div>

<div v-for='(count in 10)'> </div>
Copy the code
  • global

    Vue. Filter (‘ filter name ‘,function(){

    })

  • Private (local)

    filters:{ dateFormat:function(data,param){ do some } }

Tips:

  • Data is | the first parameter, has been dead, is always a pipeline data to be converted on the left, other parameters of param filtering methods incoming filters applied priority principle, if the private and the same name global priority use private.

  • Padstart and PADend es6 complement 0 methods

  • The second argument is a string, the third argument is an expression, and an error is reported if the custom argument value is dynamic. At present, it is simple filter with filter, complex point with method, can use computational attributes with computational attributes cache, can improve performance.

10. Key modifier

  • Listen for values on the PC keyboard

    < input@keyup. enter=’ method name ‘>

** Tips: ** Enter can be changed to any value on the keyboard, as long as to find the relevant keyboard code, can be used, recommend setting individual name. Place in a template without button action.

  • Custom global key modifier

Vue. Config, keycodes.f2 = 113, can be used

** F2 modifiers are self-created and not defined in vue

Define instructions

1. Global

Directives defined are created as specified, in bind and INSERTED, and updated

Directive ('focus'{// When a directive is bound to an element, the bind function is executed immediately, only once, Bind :function(el,binding){bind:function(el,binding){bind:function(el,binding){bind:function(el,binding){bind:function(el,binding){bind:function(el,binding){bind:function(el,binding){ El.style.color =binding.value}, // Just one inserted:function(){el.focus() js action is put here to create}, Function (){},})Copy the code

tips:

  • Parameter 1: instruction name. When defining, the instruction name does not need to be preceded by a V – prefix, but when calling, it must be preceded by a V – prefix

  • Parameter 2: is an object on which there are instruction-dependent functions that can perform related operations at a particular stage

  • The first argument in every function is always el, which stands for the element to be bind. El is the native JS object

2. The local

Directives :{' Directive name ':{bind:function(EL, B){}}Copy the code

3. The abbreviations

Function (el,binding){// Note that this function is equivalent to writing code to bind and updateCopy the code

While stylesheet directives are properly placed in bind, js directives are appropriately placed in the inserted section to prevent the directives from taking effect, and you can use this section to change styles when writing components using scenarios

12. Life cycle

  • BeforeCreate () : This is the first lifecycle function we have encountered, indicating that it will be executed before the instance is fully created

  • Created () : This is the second declared periodic function we’ve encountered

  • BeforeMount () : Templates are edited in memory but not yet rendered (mounted) to the page. BeforeMount execution, the elements in the page are not actually replaced, just some template strings that were written before. Like {{text}}

  • Mounted () : indicates that a template is mounted to the page. The page is displayed. Once this lifecycle is completed, the entire VUE instance is initialized. At this point, the component has moved out of the creation phase and into the run phase

  • BeforeUpdated () : This time indicates that our page is not fully updated, but the data is updated and the data displayed on the page is still old. At this point, the data is the latest, and the page has not been synchronized with the latest data

  • Updated () : The updated DOM tree is updated to the real page based on the latest data in data. At this point, the data (model layer) -> View (view layer) is updated, and the page and data are in sync and are up to date

  • BeforeDestroy: When the beforeDestroy hook function is executed, the vue instance moves from run to destroy. All data and all methods, filters, instructions, etc. are available on the instance, and no destruction is actually performed

  • Destroyed: All data, instructions, methods, etc. on the instance are destroyed when this function is executed

13, the transition class name to achieve animation

1. Built-in animation for Vue

<style> .v-enter, .v-leave-to{ opacity:0; Transform :translateX(150px) -- this thing is translateX}. V-enter-active,. V-leave-active {transition:all 0.4s ease; } </style> <transition name='my'> <h3 v-if="flag"></h3> </transition> <script> data(){ return { flag:false } } </script>Copy the code

2. Use third-party classes to animate

<transition enter-active-class="bounceIn"
leave-avtive-class="bounceOut"  duration='200' 

>
 <h3 v-if="flag" class="animated"  ></h3>
</transition>
Copy the code

3. Declare the js hook in the property to implement the half-court animation (only need to enter, not leave).

<transition <div @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter" > </div> </transition> <transition  <div v-show="flag" @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter" > </div> </transition> <script> Methods :{beforeEnter(el){// before animation starts, you can set the initial position of elements before animation starts in beforeEnter. El.style. transform= "translate(0,0)"}, Enter (el,done){/* This will force a refresh of the animation */ el.offsetwidth el.style.transform= "Translate (150px,450px)" el.style.transition='all 1s ease' /* Here done means afterEnter reference, AfterEnter (el){/* After the animation is complete, afterEnter */ this.flag=! this.flag } } </script>Copy the code

4. When transitioning a list, use transitionGroup instead of using transition wrap if the element is rendered in a V-for loop

<transition-group appear tag='ul'> <li v-for > <li> </transition-group> .v-enter, .v-leave-to{ opacity: 0; transform:translateY(80x); }. V-enter-active,. V-leave-active {transition: all 0.6s ease; } /* Use this to animate the next thing that is moving up to absolute */. V-move {transition:all 0.6s ease} V -leave-active{/* absolute :absolute; v-leave-active{/* absolute :absolute; } <transition mode="out-in"> <component :is="comName" > </component> </transition>Copy the code

Tips:

  1. V-enter is the initial state of the element before entry, before entry
  2. V-leave-to [this is a point in time] is the terminating state of leaving after the animation has left, at which point the element animation has finished
  3. V-enter-active [Time period of entry animation]
  4. V-leave-active [time period for leaving animation]
  5. Animated is an animation library, and the new version doesn’t seem to need to be included
  6. Duration = “{enter: 200, leave: 400}” duration= “{enter: 200, leave: 400}”
  7. Add the “Appear” property to make it look like it did when the page first appeared
  8. Using the transition-group element, set the tag attribute to render the transition-group element as the specified element. If no tag attribute is specified, render the span tag by default
  9. Mode =” out-of-in “, to prevent shadows, use mode to set the transition mode

You can add the name attribute to the Transition tag, and replace v with your name attribute value in the CSS style

14, components,

1. Use vue.extend to create global Vue components

Var coml= vue.extend ({template:'<h3> this is the component created with vue.extend </h3>'}) // The component template object created with the first argument Vue.component('myComl',coml) <my-coml><my-coml/>Copy the code

2. Use Vue.com Ponent to create components

Vue.component('mycom2',{template:'<div> <h3> ')Copy the code

3. Use template to create the component

<template id='tmp1'> <div> <h1> Here, through the template element, the component structure is defined externally, this way, there are intelligent hints of code and high volume </h1> </div> </template> Vue.component('mycom3',{ template:'#tem1' })Copy the code

4. Private Component

<template id='temp2'> <h1> This is the private login component </h1> </template> Componment :{login: {template:' TMpl2 '}}Copy the code
  • If Vue.component is used to define a global component, the component name should be humped, the uppercase hump should be changed to lowercase for reference, and the two words should be connected with –

  • Vue.component the first parameter: the name of the component, which will be referenced as a tag when the component is referenced in the future. The second argument: vue.extend creates the component where template is the content to be displayed

  • Note: Regardless of how a component is created, the component’s template attribute points to a content template that must have only one root element

15, Component data

  1. Components can have their own data
  2. A component’s data is a bit different from an instance’s data, which can be an object, but a component’s data must be a method
  3. In addition to the fact that data in a component must be a method, the method must return an object inside
  4. Data in a component is used in exactly the same way as data in an instance
  5. Why does data in a component have to be a method and return an object? Because you want to ensure that no data in the instance is unique, data in data will be shared by other instances if it is placed outside the instance.

16. Component switching

1. Switch components can be switched with V-IF and V-else, i.e. TAB switching

<a href="" @click.prevent="flag=true" > Login V-if ="flag"> </login> <register v-else="flag"> </register>Copy the code

2. Vue provides component to display the named component

// Component is a placeholder :is property that specifies the name of the component to be displayed as a string. For dynamic binding, the component name should be written as a normal key, but value must be a string. <component :is="'componentId'"> </component> <component :is="oneName"> </component> data(){ return{ oneName:"login", } }Copy the code

17. Parent-child component communication

  1. Parent components pass values, using v-bind:(:) to pass values, and props to receive values

  2. The parent component uses the event binding mechanism to pass methods to the child component V-ON – @

    // <component-name :children=’children’ // pass value @handle=’show’ // bind method in parent component

    data(){

    return(){
        children:11
    }  
      
    Copy the code

    }

    methods:{

    show(data){
          
      }
    Copy the code

    }

3. Emit, emit, emit, emit

@handle=show The parent component passes the show method to its child components

The child component receives the parent’s method and passes the child’s value to the parent using $emit

/ / child components in the methods: {handle () {enclosing $emit (' func, {age: 1, name: 'do things'})}}Copy the code

4. Add custom parameters when the parent component receives all parameters of the child component

$emit('test',this.param) // parent @test='test($event,userDefined)' 2. When a child component emits multiple parameters: // Sub component this.$emit('test',this.param1, Param2, param3) // @test='test(arguments,userDefined)'Copy the code

** The data in the child component is not passed by the parent component, but the child component itself is private, such as the child component through ajax request data, data can be placed on the data, data is readable and writable

Get the DOM element using ref

<h3 id='myh3' ref='myh3'> </h3> methods:{ getElement(){ console.log( this.$refs.myh3.innerText) } } <login ref='mylogin'> </login> methods:{getElement(){// The parent component calls the attributes in the child component console.log(this.$refs.mylogin.msg) } }Copy the code

Tips:

  1. Refs. S stands for multiple references, there will be multiple DOM elements
  2. Ref = reference Value type and reference type

19, routing,

Router-view This element is provided by vue-router and is used as a placeholder. ** When a routing rule matches a component, it is displayed in this element

<router-view></router-view>
Copy the code

2. Route switching. The template is rendered as an A label by default

The span using the tag can be used to convert the tag name of the template

<router-link to="/login" tag='span' >Copy the code

3. Configure routes

New VueRouter({// routes:[{path:'/', redirect:'/login'}, {path:'login', Component :login}, LinkActiveClass :' myActive '}) var vm=new Vue({el:'#app', data:{}, Methods :{}, router // Register the routing rule object on the VM instance to listen for Url changes and display the corresponding components. })Copy the code

4. Route parameters are transmitted

1) query

// Get id this.$route.query.idCopy the code

2) Upload the parameter in path

< router-link to="/login/12/ls" > {path:'/login/:id/:name', Component :login}Copy the code

3. Params new way to view documents

4. Zi lu by

<router-link
to="/account/login"
>
</router-link>

routes:[
{
  path:'/account',
  component:account,
  children:{
   {
   path:'login',
   component:login
   }   
  }
}

] 
Copy the code

Tips:

  • Each routing rule is an object with two required attributes
  • Attribute 1 is PATH, which indicates the listening address of the route
  • Attribute 2 is Component. If the route matches the path of attribute 1, the component corresponding to the component attribute is displayed
  • Child routes cannot add /. If you add /, the root directory will be used as the matching base
  • A hyperlink’s to must have a parent route

Note: The Component property value must be a component template object, not a component reference name

20. Named views for classic layout

Find the component by name

<router-view></router-view> <router-view name="left"></router-view> <router-view name="main"></router-view> var header={  template:'<h1>header</h1>' } var leftBox={ template:'<h1>leftBox</h1>' } var mainBox={ template:'<h1>mainBox</h1>' } { path:'/',components:{ 'default':header, 'left':leftBox, 'main':mainBox } }Copy the code

21, watch

Listen for non-DOM elements

watch:{ 'obj.a'(newValue,oldValue){ }, immediate:false } watch:{ 'obj':{ handler (newValue, oldValue) { } }, $route.path :{handler (newValue, oldValue) {}}, //immediate:true indicates that the handler method is executed immediately after the declaration is made in wacth. If the value is false, the handler method is not executed immediately.Copy the code

Tips:

  • Obj = handle+immediate:true; obj = handle+deep:true; obj = handle+deep:true
  • The handle method can be used to make watch execute upon initialization. If handle is not used, it will not be executed until data adaptation
  • Do not modify the values being computed or monitored in Watch or Computer, but generate new values

22, the computed

computed:{
 'fullname':(){
  return 
 }
}
Copy the code

The render function registers the component (attributes of vm[vue instance]).

Render :function(createElements){return createElements(login) // pay attention to this The result of return replaces the container specified by el in the page}Copy the code

Render can only place one render component in an app, components can place multiple and not override

24

1. Write slot

<div v-if="layout === 'block'" class="layout-block" :class="scroll? 'layout - scroll' : ' '" > < slot > < / slot > / / anonymous slot < / div > <! <div v-if="layout === 'both'" class="d-flex JC-between "> <div class="layout-both" :class="scrollLeft? 'layout-scroll':' ">< slot name="left"></slot> // named slot </div> <div class="layout-both" :class="scrollRight? 'layout-scroll':''"> <slot name="right"></slot> </div> </div>Copy the code

2. Use slots

</template> <template v-slot="left" ></template>Copy the code

Second, the miscellaneous

1, the NRM

Install the NRM

  • NRM I NRM -g Global installation
  • NRM ls Displays the list
  • NRM use NPM There are many addresses to choose from after using NRM use

Tips: NRM simply provides a few common url addresses for downloading packages and allows us to switch easily between them, but the reality is that the installation tool we use every time is NPM and NRM

npm i cnpm -g 
Copy the code

2, webpack

What common static resources are referenced in a web page:

  • Js (.js.jsx.coffee.ts)
  • CSS (.css.less.sass.scss)
  • Image (.jpg.png. GIF. Bmp.gif)
  • Fonts (.svg.ttf.eof.woff.woff2)
  • Template file (.ejs.jade.vue)

3. Hot deployment

Webpack-dev-server implements automatic packaging, so that the browser can see that the file has been modified without refreshing it. The packaged file is not placed on the actual physical disk, but directly hosted in the computer memory. The packaged file is nowhere to be found in the root directory of our project. It is a file visible at the SRC, dist, node_modules levels

4. Hot update

Hot pages do not reload, update directly, speed up packaging speed does not generate new files

 "scripts":{
   "dev":"webpack-dev-ser  ver --open --prot       3000 --contentBase src --hot "     
 }
Copy the code

Hot update configuration in the configuration file

   devServer:{
     hot:true 
}
Copy the code

5. Webpack introduces VUE

In Webpack, import the Vue using the following method

The runtime-only constructor is not fully functional and does not provide a way to use it in a web page

Castration version:

import Vue from ‘vue’

Complete version

1. import Vue from '.. Module. exports={resolve:{"vue$":"vue/dist/vue. Js "}}Copy the code

Tips: Rules for finding packages

  • See if node_modules exists in the project root directory

  • In node_modules, locate the vue file based on the package name

  • In the vue folder, locate the package.json package configuration file

  • Look for the main property in package.json (the main property specifies the entry file in which the package is loaded)

  • Package changes to WebPack require a rerun of the project

6. Render components in webpack

If you want to display a component on a page via vUE, the RENDER function in the VM instance can do that

Render :function(createElement){return createElement(login)} render:function(createElement){return (login)}Copy the code

Tips: How to use VUE in Webpack

  1. Install the vue package
  2. Since.vue is recommended to define components in Webpack, a parsed Loader needs to be installed
  • Import vue from ‘vue’
  • Define a. Vue component that consists of three parts
  • Import the login component using import login from ‘./login.vue’
  • Var vm = new Vue({el:’app’,render:c=>c(login)})
  • Create a div element with the ID app on the page as the control area for the VM instance

7. Export default and export

  • Members exposed by export Default can be received using any variable

  • Export Default is allowed to be exposed only once in a module

  • In a module, you can use both Export default and export to expose members

  • Members exposed using export can only be received as {}. This method is called (export on demand)

  • Export can expose multiple members. If we do not need some members when importing, we may not define them in {}

  • Caution Members exported using export must be received on demand using {} in strict accordance with the exported name

  • Members exported using export can be aliased using AS if they want to receive with a different name

    Const arr={a:’1′, b :’ 2′} export default arr

    /* export default {address:’ Beijing ‘} */

    export title=1 import arr, {title as title1 } from ‘/xxx.js’

8 the router.

  • Render will overwrite everything in the container specified by el, so don’t write router-view and router-link routes directly to elements controlled by EL

  • Note that the app component is rendered by the RENDER function of the VM instance. If the render function is used to render groups, the result of the render can only be placed in el:”#app”, el specified in #app.

  • The Account and goodList components are monitored by route matching and can only be displayed for the route to which they belong

  • The application scenario of the child route changes on the TAB page

9. Scoped principle

Style scoped is implemented via CSS property selectors. Aa [VSFP]{color:red}

Tips: VSFP is a hash

10, promise

  • To simulate the promise

    getFution(aa,callback){ callback(aa)

    }

    getFution(aa,funtion(res){ console.log (aa) })

  • Asynchronous operations

Whenever a new Promise instance is created, the code in this asynchronous operation is immediately executed.

That is, in addition to getting a Promise instance, new immediately calls the function passed by the Promise constructor and executes the asynchronous operation code in that function.

Var promise=new promise (resolve (true) reject(false)}) var promise=new promise (function(reject(true)) Var promise=new promise (function(){getFunction(aa)}. Then (function(data){ Console. log(data) return getFunction() -- Use subsequent then}. Then (function(data){console.log(data)\ return GetFunction ()}).then(funtion(data){console.log(date)}) // Capture is only placed at the end. .catch(function(data){console.log(data)}Copy the code

It is not advisable to write multiple methods that return errors in ‘then’

11, vuex

Vuex is created to save the data shared between components. If the data is to be shared between components, it can be directly connected to vuex without transferring values between parent and child components. If the data of components does not need to be shared, it is unnecessary to put the private data that does not need to be shared in VUex

Vuex stores shared data

Data Stores private data

Props holds data from the parent component

Operate state in vuex

Manipulating property values directly in store is not recommended

This $store. State. Property values

  • It is recommended that only the method provided by mutations can operate the corresponding data

    Mutations :{increment(state,payload){state.count++}} this. codestore.com MIT (‘ method name ‘)

  • Vuex getters

    Getters is recommended if state data in the store needs to be wrapped when it is provided externally.

    optCount:state=>state.count
    this.$store.getters.***
    
    Copy the code

Tip: The state in increment method is the state in VUEX; Count is an attribute in state; Payload An external value that changes the value of an attribute in state. A maximum of two arguments can be supported, which can be arrays and objects

12, ngrok

You can map local port 80 to map the local address to an external address

NPM address:

NPM install ngrok -g NPM install ngrok HTTP 80Copy the code

Tips: Need to start the local server, after mapping only mapping WWW path, not completed program path, need to supplement their own complete.

13, How to require images in the public directory

// img: require("@/.. / public/img/home/user. JPG ") / / second Here you can put the front/as a public/img/abnormal/Trash. PNG namely public/img/abnormal/Trash. PNGCopy the code

Tips: @ refers to the SRC directory.. The directory above @, before entering public

3. Performance optimization suggestions

1. If watch is obj and handle+deep:true, it can also listen to the properties of the object, but it consumes a lot of performance

2. Values generated in computed data are cached. It is not recommended to use functions to compute some values, because computed data has higher performance

3, : key = “id”

  • Id is the id returned from the list. If there is no ID, write item, index is not recommended (esLint will get a warning). Writing key will reduce cache consumption

4. The difference between V-once and V-Model is that v-once only binds once and does not update the content. You can reduce your overhead

  • Application scenario: In the read-only scenario, the page is not modified

5. V-for and V-if are not appropriate to use in the same div

  • This can be done by using a template on the outermost layer

6, this.$parent can change the value of the parent component, but is not recommended

Gzip optimization

  • Vue configuration, generate files with GZ in the front end

  • Auxiliary plug-in: Compression -webpack-plugin

    const CompressionWebpackPlugin = require(‘compression-webpack-plugin’) const productionGzipExtensions = [‘js’, ‘css’] const isProduction = process.env.NODE_ENV === ‘production’

    configureWebpack: config => { if (isProduction) { config.plugins.push( new CompressionWebpackPlugin({ algorithm: ‘gzip, test: new RegExp (‘ \. (‘ + productionGzipExtensions. Join (‘ |’) + ‘) $’), the threshold: 10240, minRatio: 0.8}}})),

Nginx server configuration

/ / cooperate with front-end gzip on site configuration to add the following code: the location ~ * \ | js (CSS) ${gzip_static on; } This is the static gzip function of nginx, which automatically looks for the file with the corresponding extension. If there is a gzip file, use the original file. gzip_static on; gzip_min_length 1k; gzip_buffers 4 16k; Gzip_http_version 1.1; gzip_comp_level 2; gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml; gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_disable "MSIE [1-6]\.";Copy the code

8. CDN acceleration

< script SRC = "https://unpkg.com/[email protected]/dist/vue.runtime.min.js" > < / script > < script SRC = "https://unpkg.com/[email protected]/dist/vuex.min.js" > < / script > < script SRC = "https://unpkg.com/[email protected]/dist/vue-router.min.js" > < / script > < script SRC = "https://unpkg.com/[email protected]/dist/axios.min.js" > < / script > < script SRC = "https://unpkg.com/[email protected]/lib/index.js" > < / script > / configureWebpack had config in the following configuration: config => { //cdn config.externals = { vue: 'Vue', vuex: 'Vuex', 'vue-router': 'VueRouter', axios: 'axios' } if (isProduction) { config.plugins.push( new CompressionWebpackPlugin({ algorithm: 'gzip', test: New RegExp (' \ \. (' + productionGzipExtensions. Join (' | ') + ') $'), the threshold: 10240, minRatio: 0.8}}}))Copy the code

9, the introduction of static resources in the webpage after what will be the problem?

  • Web pages load slowly because there are so many secondary requests
  • There are intricate dependencies to deal with
  • Solution:
  1. Merge, compress, Sprite, base64 encoding of pictures, CDN
  2. We can use the requireJs we learned previously, or we can use webpage

10. Set up different environment variables (development, test, formal)

Create 3 files in the package.json directory: env.development -- local environment 2. Env.production -- formal environment (formal server -- package) 3 /*****. Env. development file contents *****/ NODE_ENV = 'development' VUE_APP_CURRENT_MODE = 'development' /*****. Env. production Contents of file *****/ NODE_ENV = 'production' VUE_APP_CURRENT_MODE = 'production' /*****. Env. test*****/ NODE_ENV = 'production' VUE_APP_CURRENT_MODE = 'test' In pure vue_cli3.x configure the following "scripts": {"serve": "vue-cli-service serve --mode development", "build": "vue-cli-service build --mode production", "build:test": "vue-cli-service build --mode test", }, 2. Vue_cli3. x "scripts": {"serve": "NPM run dev:h5 -- development", // modify "build": NPM run build:h5 -- production", NPM run build:h5 -- production", "Cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-build --mode", "cross-env NODE_ENV=production UNI_PLATFORM=mp-alipay vue-cli-service uni-build", "build:mp-baidu": "cross-env NODE_ENV=production UNI_PLATFORM=mp-baidu vue-cli-service uni-build", "build:mp-toutiao": "cross-env NODE_ENV=production UNI_PLATFORM=mp-toutiao vue-cli-service uni-build", "build:mp-weixin": "cross-env NODE_ENV=production UNI_PLATFORM=mp-weixin vue-cli-service uni-build", "dev:h5": "Cross-env NODE_ENV=development UNI_PLATFORM=h5 uE-cli-service uni-serve --mode", // modify point "dev:mp-alipay": "cross-env NODE_ENV=development UNI_PLATFORM=mp-alipay vue-cli-service uni-build --watch", "dev:mp-baidu": "cross-env NODE_ENV=development UNI_PLATFORM=mp-baidu vue-cli-service uni-build --watch", "dev:mp-toutiao": "cross-env NODE_ENV=development UNI_PLATFORM=mp-toutiao vue-cli-service uni-build --watch", "dev:mp-weixin": "cross-env NODE_ENV=development UNI_PLATFORM=mp-weixin vue-cli-service uni-build --watch", "info": "node node_modules/@dcloudio/vue-cli-plugin-uni/commands/info.js" },Copy the code

The main change point is mode — ‘environment variable’.

Iv. Introduction and reference of various plug-ins

1, the plugin postcss – – px2rem

Postcss.config. js vue-cli3.x Scaffolding comes with units such as PX to REM configuration.

module.exports = { plugins: [ require('autoprefixer')(), require('postcss-plugin-px2rem')({ rootValue: 192, // Width of design drawing /10 unitPrecision: 10, // Conversion rem reserves several decimal points mediaQuery: true, minPixelValue: 3 / / exclude: / node_modules | folder_name/I, the framework of the third party rule out]}})Copy the code

2, the Babel – plugin – transform – remove the console

Delete console, create a new. Babelrc file in the root directory, and configure:

{/ / the first one "env" : {" production ": {" plugins" : [[" transform - remove - the console, "{" exclude" : [" error ", "warn"]}]]}}}Copy the code

3, HTML – webpack – the plugin

When using the HTML-webpack-plugin, we do not need to manually postprocess the bundle.js reference path. Because the plug-in has automatically created an appropriate script and referenced it correctly

*/ const htmlWebpackPlugin=require("html-webpack-plugin") // Create an in-memory HTML plugin New htmlWebpackPlugin({template:path.join(__dirname,'./ SRC /index.html') filename:'index.html'}) // This node is used to configure all Third party module loader module: {rules: [{test: / \. CSS $, use: []}]}Copy the code

4, prerender – spa – the plugin

The build phase generates HTML files that match the pre-rendered path