The first part is Vue knowledge framework

0. Meet the Vue

Vue is pronounced like view

Incremental Vue

Vue characteristics

1. How do I install it

  • Method 1: Direct CDN introduction
  • Mode 2 download and import
  • NPM install

2.HelloWorld

Programming paradigm: declarative programming

<div id="app">{{message}}</div> <script> }}) </script>Copy the code

Contrast previous native JS development (imperative programming)

  • 1. Create a div element and set the ID attribute
  • 2. Define a variable called message
  • 3. Display the message variable in the previous div element
  • 4. Modify message’s data: It’s a beautiful day today
  • 5. Replace the modified data with the div again

3. What is MVVM

Model ViewModel View

The * View is still our DOM * Model that we pulled out and the * OBj * ViewModel is the View instance that we createdCopy the code

How do they work with each other

First, the ViewModel uses Data Binding to display obJ Data in the DOM in real time. Second, the ViewModel listens for DOM events through DOM Linstener and changes obJ Data through operations in MethodsCopy the code

4. Current options

  • el

    Type: string | HTMLElement role: to decide which a Vue instance will manage the DOMCopy the code
  • data

    The role type: Object | Function: Vue instance corresponding dataCopy the code
  • methods

    Type {[key: string] : function}Copy the code

When is a method in development? When is it called a function

Essential difference: Methods are tied to instance objectsCopy the code

5. Basic grammar

(1) Mustache

{{}}—-> Experience the responsiveness of vUE

Interpolate related instructions

  • v-once

    <h2 v-once> {{message}} </h2>Copy the code
  • v-html

    < h2 v - HTML = "url" > < / h2 > data: {message: "hello," url: '< a href = "http://www.baidu.com" > baidu about < / a >'}Copy the code
  • V-text is like Mustache

  • v-pre

    <h2 v-pre>{{message}}</h2Copy the code
  • Before vue is parsed. div has a V-cloak so we can use v-cloak to write some style

    <div id="app" v-cloak> <! -- --> {{message}} </div> [v-cloak]{ display: none; }Copy the code

(2) v – bind

Bind properties to dynamically bind one or more attributes, or a component prop, to an expression.

  • Binding basic properties:

    v-bind:src
    :href
    Copy the code
  • Abbreviations: :

<img v-bind:src="imgUrl" alt="">

<img :src="imgUrl" alt="">

  • V-bind dynamically binds the class attribute

Two kinds of

* Object syntax * array syntaxCopy the code

Object syntax

We can pass v-bind:class an object to dynamically switch classes:

<div v-bind:class="{active: isactive}"> </div> <div class="title" v-bind:class="{active: Isactive,line:isLine}"> If it's too complicated, you can put it in a methods or computed method <div V-bind :class="getClasses()"> ha-ha-ha </div> getClasses:function(){return {active: this.isactive ,line:this.isLine} }Copy the code

Array syntax

< div class = "title" : class = "[' active 'and' line ']" > ha ha ha ha ha < / div >Copy the code
  • V-bind dynamically binds style

The v-bind:style object syntax is straightforward — it looks a lot like CSS, but it’s actually a JavaScript object.

Two kinds of

* Object syntax * array syntaxCopy the code

Object syntax

<! -- 59px must be in single quotes, Or as a variable resolution - > < h2: style = "{fontSize: '50 px'}" > {{message}} < / h2 > < h2: style = "{fontSize: size}" > {{message}} < / h2 > < h2 :style="{fontSize:finalSize+'px'}">{{message}}</h2>Copy the code

Array syntax

<div V-bind :style="[baseStyles, overridingStyles]">hhahahhah</div> data: { baseStyles:{backgroundColor:'red'}, overridingStyles:{fontSize:'100px'} }Copy the code

(3) Calculate attributes

When we need to transform data or combine multiple data to display, the code written directly inside {{}} looks unreadable

  • Calculate setters and getters for properties

    // fullName:function(){// return this.firstname + "+ this.lastname //} We don't want someone to just give us the value of the evaluated property without the set property, This is read-only fullName:{set:function(){}, Get :function(){return this.firstName+ "+ this.lastName}} fullName:{set:function(newValue){fullName:{set:function(newValue){ console.log("-----",newValue) const name=newValue.split(" ") this.firstName=name[0] this.lastName=name[1] }, get:function(){ return this.firstName+ ' '+ this.lastName } }Copy the code
  • 2. Comparison between calculated attributes and Methods

    <! <h2>{{firstName}} {{lastName}}</h2> <! -- The second option: By defining methods functions, Then call the function --> <h2>{{getFullName()}}</h2> methods:{getFullName(){return this.firstName+" "+this.lastName}}, <! -- The third option: Computed attributes --> <h2>{{fullName}}</h2> computed attributes, Function (){return this.firstName+" "+this.lastName}} fullName:function(){return this.firstName+" "+this.lastName}} If firstName and lastName are not changed on each call, it returns the result of the last callCopy the code

(4) Supplement ES6 knowledge points

  • let/var

    Var in ES5 has no block-level scope

    Lets in ES6 are block-level scoped

    Variable scope: The extent to which a variable can be used without block-level scope effects: The if block level there is no scope, cause problems for the block-level no scope function scope var BTN = document. The getElementsByTagName (" button ") / / for (var I = 0; i<btn.length; I ++){// BTN [I].adDeventListener ("click",function(){// console.log(" + I +"){// for has no block-level scope, All I references the same variable //}) //} // i<btn.length; I++) {(function (I) {BTN [I] addEventListener (" click ", function () {the console. The log (" first "+ I +" button was clicked ")})}) (I)} Brendan Eich, the designer of JS, didn't think much about var, which was a defect, so he added the keyword: let let has block-level scopeCopy the code

Conclusion:

Before ES5, because we didn't have block-level scope for if and for, we often had to resort to function scope to solve the problem of applying outside variables. In ES6, we added let, For (let I =0; for(let I =0; i<btn.length; I ++){BTN [I].adDeventListener ("click",function(){console.log(" + I +"){BTN [I].adDeventListener ("click",function(){console. All I references the same variable})}Copy the code
  • const

    constant

    const a=30 a=40; // Error, cannot modify const name; // Error, const identifier must be assignedCopy the code

    Constant means that the object you point to cannot be modified, but you can change properties inside the object

  • ES6 object literals enhance syntax

    What is an object literal?

          const obj={}
          
    Copy the code

    An enhanced writing of the property

    const name='vina'; Const obj={name:name, age:age} const obj={name, age, age}Copy the code

    Enhanced writing of a function

    / / ES5 writing const obj = {the run: the function () {}, eat: function () {}} / / enhance writing const obj = {the run () {}, eat () {}}Copy the code

(5) v – on

  • Function: Bind event listener

  • Abbreviations: @

  • Expectations: the Function | Inline Statement | Object

  • Parameters: the event

    <button v-on:click="counter++">+</button> <button v-on:click="counter--">-</button> <button V-on :click="increment()">+</ rement > </ rement @click="decrement">+</ rement >Copy the code
  • The V-ON parameter problem

    The method called by the event has no parameters

    Analysis: When the event method has no parameters, <button @click="btn1Click()"> </button> <button @click="btn1Click()"> </button> btn1Click(){ console.log("btnClick") },Copy the code

    In the function event definition, the parentheses are omitted when the function is written, but the method itself requires an argument

    Analysis: If the method itself requires an argument, but the method is called with no argument and no parentheses, the event event is printed, </button> <button @click="btn2Click()"> 4 </button> btn2Click(a){ console.log(a) }Copy the code

    When we define a method, we need the event event, and we need extra parameters.

    < button@click ="btn3Click($event,123)"> 5 </button>Copy the code
  • V – on the modifier

.stop

<div @click="divClick"> <! < button@click. stop="btnClick"> </button> </div>Copy the code

.prevent

The form itself commits, so if we want to write the commit method ourselves, then we have to prevent the default commit event, <form action="baidu"> <input type="text"> <input type=" value "="submit" @click.prevent="submitClick">  </form>Copy the code

.keyUp listens for all events

<! - listen to a keyboard (all) the keys of the cap - > < input type = "text" @ keyup = "keyup" > <! <input type="text" @keyup. Enter =" keyup ">Copy the code

. Once Triggers only once

  <button @click.once="onceClick">once</button>
  
Copy the code

(6) Conditional judgment

  • v-if
< h2 v - if = "score > = 90" > good < / h2 > < h2 v - else - if = "score > = 80" > good < / h2 > < h2 v - else - if = "score > = 60" > in < / h2 > < h2 v - else > fail < / h2 >Copy the code
Analysis: this is not recommended when there are many conditions, we can write in the calculation attributeCopy the code

Why do I enter the content, but switch the input field, the data still exist?

Analysis: This is because when Vue renders DOM, it is reused rather than recreated for performance reasons

<span v-if="isUser"> <label for="username"> </label> <input type="text" ID ="username" placeholder=" username"> <span v-else> <label for="email"> </label> <input type="text" ID ="email" placeholder=" placeholder "> </span> <button @click="checkStatus"> </button>Copy the code

Solution: What can I do if I do not want to switch the input field and the original data still exist

Let's add a key to each input fieldCopy the code
  • V – show and v – the if

    v-if

    When the condition is false, the element containing the V-if instruction does not exist in the DOM at allCopy the code

    v-show

    When the condition is false, the V-show directive simply adds an inline style display: None to our elementCopy the code

    How to choose during development?

    When we need to slice between show and hide very frequently, use v-show when there is only one switch, usually choose V-if, v-if is used a lot in development, we usually take the data sent by the server to determine whether to render.Copy the code

(7) Loop traversal

  • V-for traversal number group

    <li v-for="item in names">{{item}}</li> Get index values < li v - for = "(item, index) in names" > {{index + 1}} : {{item}} < / li >Copy the code
  • V-for traverses the object

    <li v-for="item in info">{{item}}</li> <! Get key and value --> <! - (value, key) - > < li v - for = "(key, value) in the info" > {{value}} -- -- -- -- -- - {{key}} < / li > <! - h to get the key, the value, the index - > < li v - for = "(the value, the key index) in the info" > {{index}}, {{value}} -- -- -- -- -- - {{key}} < / li > info: {name: "according to", Age: 19, height: 1.88}Copy the code
  • The component’s key property

    It is recommended to add a key attribute to the corresponding element when using V-for for better reuse

    We need a key to give each node a unique identity

    Diff algorithm can correctly identify the secondary node find the correct location to insert a new nodeCopy the code

    Therefore, the main use of keys is to update the virtual DOM efficiently

(8) which methods in the array are reactive

Vue internally listens for data changes and re-renders DOM push, POP, unshift, Shift, Reverse, splice, splice, delete elements, insert elements, modify elements if you want to delete elements: Splice (start) this.letters.splice(1,2) delete all this.letters.splice(2) if I want to replace three elements This. Letters. Splice (1, 3, '1', '2', '3') new elements, as long as the second element of 0 this. Letters. Splice (1, 0, '1', '2', '3')Copy the code

(9) Higher-order functions

So let’s look at the code that we need to do some of the things that we need to do before we learn higher-order functions

/ / requirements: Const nums=[1,2,3,4,5] let newNums=[] for(let n of nums){if(n<100){newnums.push (n)}} Console. log(newNums) *2 let new2Nums=[] for(let n of newNums){new2nums.push (n*2)} console.log(new2Nums) Let total=0 for(let n of new2Nums){total+=n} console.log(" loop method ",total)Copy the code

After learning higher-order functions, our requirement implementation code is as follows

let Total=0 Total =nums.filter(function(n){ return n<100 }).map(function(n){ return n*2 }).reduce(function(pre,value){ Return pre+value}) console.log(" high order function ",Total)Copy the code

Analysis: Filter, Map, and Reduce

The callback function in filter has a requirement that it must return a Boolean value. If it returns true, n is automatically added to the new array value. If it returns false, n is automatically filtered from the callback in the n mapCopy the code

Arrow function result = nums. Filter (n = > n < 100). The map (n = > n * 2). Reduce ((pre, val) = > pre + val)

(10) Form binding V-Model

  • Basic operation:

       <input type="text" v-model="message">
    Copy the code
  • Nature:

The V-Model is a syntactic sugar that essentially contains two operations behind it

<input type="text" V-bind :value="message" V-on :input="valueChange"> valueChange(event){ this.message=event.target.value }Copy the code
  • Abbreviations:

    <input type="text"  v-bind:value="message"  v-on:input="message=$event.target.value">
    Copy the code
  • Syntactic sugar

    <input type="text" :value="message"  @input="message=$event.target.value">
    Copy the code

V – model: radio

  • Value binding

    Value binding is a dynamic assignment to a value, because in real development, these input values may be network-fetched or defined in data

    <label v-for="item in originHobby" :for="item"> <input type="checkbox" :id="item" :value="item" V - model: value = 'hobby' > {{item}} < / label > originHobby: [' badminton ', 'basketball', 'a trampoline,' diving ', 'the piano']Copy the code
  • V – model modifier

    lazy

    number

    trim

    <! Lazy bidirectional binding disadvantage: <input type="text" v-model. Lazy ="message"> {{message}} <! Sometimes we want the user to enter a number. We can change the input type to number, but the data is still a string --> <! -- <input type="number" v-modal="num"> {{typeof num}} --> <! We can add the number modifier when we want the data to be of type number, <input type="text" v-model. Number ="num"> {{typeof num}} <input type="text" v-model="name"> {{name}} <input type="text" v-model.trim="name"> {{name}}Copy the code

6. Modular

We can divide the bandits' complete page into multiple components, each of which implements its own corresponding module's functionsCopy the code

(1) Vue componentization thought

Vue componentization idea

It provides an abstraction that allows us to develop individual reusable widgets to construct our application and any application is abstracted into a tree of componentsCopy the code

Application of componentization

With the idea of componentation, we should make full use of it in the later development as far as possible to break the page into small, reusable components so that our code is more convenient to organize and manage, and the expansion is stronger. Therefore, component is a very important chapter in Vue development, to learn seriouslyCopy the code

Component usage steps

  • Create the component constructor

  • Certified components

  • Using the component

    Vue.extend() creates a component constructor for components. Vue.component() registrates components in the scope of Vue instances const cpnC= vue.extend ({template: '<div> <h2> I'm the title </h2> Vue.component('my-cpn', cpnC) </h2> </h2> </div> '}Copy the code

Register component step resolution

1, Vue. The extend () : We call vue.extend () to create a component constructor and usually when we create a component constructor, we pass in the template that represents our custom component and that's where we use the component, When Vue.component() calls Vue.component(), it registers the constructor as a component and gives it the tag name of a component, passing two arguments: Component constructor. Component must be mounted on a Vue instance, otherwise it will not take effectCopy the code

(2) Global and local components

Vue.com components ('my-cpn', cpnC) components:{CPN :cpnC}Copy the code

(3) Parent and child components

There is a hierarchy between components

One of the most important relationships is the parent-child component

(4) Register component syntax sugar

Create the component and register the component

Const cpnC= Vue. Extend ({template: '<div> <h2> I am the title </h2> <h2> I am the content, hahahahaha </h2> <h2> I am the content, Ha ha ha ha < / h2 > < / div > `}) Vue.com ponent (' my - CPN, cpnC)Copy the code

Create component syntax sugar schema

Vue.component('my-cpn', {template: '<div> <h2> I am the title </h2> <h2> I am the content, hahahahaha </h2> <h2> I am the content, </h2> </div> '}) // Register local component const app=new Vue({el:"#app", data: {}, components: {' group: {template: ` < div > < h2 > I am a title < / h2 > < h2 > I am content, ha ha ha ha ha < / h2 > < h2 > I am content, ha ha ha ha < / h2 > < / div > `}}})Copy the code

(5) How to extract the component template

(1) The first: with the script tag, the type must be text/x-template, and give the template an ID so that it can be bound to the instance

(2) add an ID to the template tag

(6) Can components access Vue instance data?

Can not access

The Vue component should have its own place to save data !!!!

Component objects also have a data attribute (or methods), but the data attribute must be a function that returns an object that holds data inside itCopy the code

(7) Why must the component data function

When creating a component, the data function is called, and each time I call it, I create a new function, data

(8) Father-son component communication

  • Props ->properties(abbreviation) Parent —-> child
  • Send a message to the parent component via the event child —–> parent

* (1) Parent passes child through props

The first way:

 props:['cmovies','cmessage']
Copy the code

Second way: type restriction

props:{
  cmovies:Array,
  cmessage:String
}
Copy the code

Third way: with default values, mandatory properties

Functions :{cmovies:Array, cMessage :String CMessage :{type:String, default:'HHHHHH', required:true}}Copy the code

* (2) Son passes to father

If the child component passes events or data to the parent component, we need to customize the timing to do so

When do you need a custom time?

Custom events are used when a child component needs to pass data to its parent. The V-ON we learned earlier can be used not only to listen for DOM times, but also for custom events between componentsCopy the code

The flow of custom events

In the child component, emit events via $emit() in the parent component, <template id=" CNP "> <div> <button V-for ="item in categories" @click="btnclick(item)" > {{item.name}} </button> </div> </template> methods:{ btnclick(item){ console.log(item) this.$emit('itemclick',item) } }Copy the code

(9) Parent-child component communication – combined with bidirectional binding events

(10) Access mode of parent and child components:$childrenor$refs(reference: quote)

Sometimes we need the parent to access the child directly, the child to access the parent directly, or the child to access the root.

  • Parent component accessing child component: use$childrenor$refs(reference: quote)
  • Child components access parent components using: $parent

Father visit the son

'this.$children' is not commonly used in development, because there is no way to determine the number of children, and the length of this.$children may change. Ref '< CPN ref="aaa"></ CPN >Copy the code

Child access to the father

This.$parent accesses the parent. This.$root accesses the rootCopy the code

(11) Slot slot

Why slot?

Let our original devices have expansibility, similar to the COMPUTER USB, can be used as power sockets, U disk, keyboard, mouse, audio and other equipmentCopy the code

Slots for components

<template id=" CPN "> <div> <h2> I'm a component </h2> <p> I'm a component hahaha hahaha </p> <! --> <slot></slot> </div> </template>Copy the code

How to package it properly?

Extract commonness, retain differenceCopy the code

A named slot

< template id = "CPN" > < div > < / h2 > < h2 > I am component < p > I'm component ha ha ha ha ha ha ha < / p > <! - named slot - > < slot name = "left" > < h2 > l < / h2 > < / slot > < slot name = "center" > < h2 > < / h2 > in < / slot > < slot Name = "right" > < h2 > < / h2 > right < / slot > < / div > < / template > < CPN > < button slot = "left" > the < / button > < span </span> <button slot="right"> </button> </ CPN >Copy the code

Compile scope

Official rule: Everything in the parent component template is compiled in the parent scope; Everything in the subcomponent template is compiled in the subscope

<div id="app"> <! IsShow or component? Answer: example --> <! < CPN v-show="isShow"> </ CPN > </div>Copy the code

Scope slot

Summary: The parent component replaces the label of the slot, but the content is provided by the child componentCopy the code

The parent component gets the child component’s data

7. Front-end modularization

(1) Modular basis

  • Why modularity

    JavaScript native features

    In the early days of web development, WHEN JS was a scripting language for simple form validation and animation implementation, there was very little code in those days when the code was written in script tags and with the advent of Ajax asynchronous requests, there was a separation of the front end and the back end and the client had to do more and more things, In order to cope with the increasing volume of code, we often organize the code into multiple JS files for maintenance. However, this maintenance method still can not avoid some catastrophic problems, such as the global variable with the same nameCopy the code

    We use anonymous functions, which solve naming conflicts but not code reusability

    So using modules as exits, we can expose variables that need to be exposed as exits of a module, meaning as follows:

    Inside an anonymous function, you define an object, add attributes and methods to the object that need to be exposed outside of the band (no explicit definition is required), and then return the object and receive it outside using ModualeA. This is the most basic encapsulation of modularityCopy the code

    As the front end becomes more complex, we don’t need to use anonymous function modularity to solve the problem, many people have written some formal modularity

    Common modular specifications

    CommonJs, AMD, CMD, and ES6 ModulesCopy the code
  • CommonJS (Understand)

    Modular core: Import and export

    Derivation of the CommonJS

         module.exports={
             flag:true,
             test(a,b){
                return a+b
             },
             demo(a,b){
                return a*b
             }
        }
    Copy the code

    CommonJS import

    Let {test,demo,flag}=require('moduleA') is equivalent to let mA=require('moduleA') let test= ma.test let demo= ma.demo let flag= ma.flagCopy the code
  • Modularity of ES6

    The export directive is to export the interface provided by our module. Now we can load the module by using the import command

    First we need to introduce two JS files into the HTML code and set type to module

      <script src="aaa.js" type="module"></script>
      <script src="ccc.js" type="module"></script>
      
    Copy the code

    The import directive is used to import the contents of a module, such as main.js code

    Import {flag, num1, height, the mul, sum, Person} from '. / aaa. Js' / / this import said import triple-a. Js export by default content inside, Import * as aaa from './aaa. Js' console.log("aaa",aaa) import * as aaa from './aaa.Copy the code

    The export directive is used to export

    Export {name,age,flag} export var num1=1000; Export var height=200. Export function mul(num1,num2){return num1+num2} export class Person{run(){console.log(' running ')}} Export default const Address =' Beijing '// In development, the default export can only have one export default addressCopy the code

    Note: Multiple export defaults cannot exist in the same module

8.webpack

Description of content

* Understand webpack * webpack installation * Webpack start * Webpack configuration * webpack use * Webpack configuration Vue * Plugin experiment * build local serverCopy the code

(1) What is Webpack

Officially, Webpack is a static module packaging tool for modern JavaScript applications

  • Front-end modularization

    Earlier we looked at several front-end modularization solutions: AMD, CMD, CommonJS, ES6 specification, currently can only use ES6, the reason is that the browser only supports ES6 specification, the browser does the underlying support of ES6, but can use AMD, CMD, CommonJS in webpack, it will automatically convert the code when packaging. Convert to modularity that most browsers recognize, so there is no AMD, CMD, CommonJS code in the package, which we use for development. Webpack does the underlying support! Before ES6, if we wanted to do modular development, we had to use other tools that allowed us to do modular development and then after we finished the project with modular development, we had to deal with dependencies between modules and one of the core things about WebPack was that it allowed us to do modular development, And it helps us deal with dependencies between modules and not just JS files, our CSS, images, JSON files and so on can be used as modules in Webpack. That's the idea of modularity in WebPackCopy the code
  • packaging

    Understand the webpack can help us to modular, and deal with the complex relationship between modules, the concept of packaging is very well understood Is to all kinds of resources in the webpack packing synthesis of one or more packages And in the process of packaging, also can be treated for resources, such as image compression, converting SCSS ES5 grammar, Convert TS to JS and so onCopy the code
  • Webpack vs. Grunt /gulp

    But it seems grunt/gulp can also help us with packaging. What’s the difference?

    The core of gulP is Task

    We configure a list of tasks and define the transaction (ES6, TS conversion, image compression, SCSS conversion to CSS) for the task to be executed once by Grunt /gulp and automate the whole processCopy the code

    When do you use grunt/glup?

    If your engineering dependencies are very simple and you don't even use the concept of modularity just simple merge, compress, use Grunt/GLup but if the whole project is modularized and the interdependencies are very strong, we need to use the most powerful tool, WebPackCopy the code

    So, what’s the difference between Grunt /glup and Webpack?

    Grunt/Glup puts more emphasis on the automation of front-end processes. Modularization is not its core webpack, and modularization development management is emphasized, while file compression merging and pre-processing are its additional functionsCopy the code

(2) Webpack and Node and NPM relationship

In order for Webpack to run properly, it must rely on the Node environment

In order to run a lot of code normally, the Node environment must rely on various packages. Manual management is too troublesome. Therefore, the NPM tool is automatically installed during node installation.

(3) Webpack installation

  • To install WebPack, you first need to install Node.js, which comes with the package management tool NPM

  • Check your Node version

  • Install webpack globally (version 3.6.0 is specified here because Vue CLI2 depends on that version)

  • Partial installation of Webpack (required later)

    — Save-dev is a development-time dependency and does not need to be used after the project is packaged

  • Why do you need a local installation after a global installation?

    When scripts is defined in package.json, which contains the webpack command, then local webpack is usedCopy the code

How to package Webpack?

   webpack ./src/main.js ./dist/bundle.js
   
Copy the code

Bundle. js is a js file generated by Webpack after handling the dependencies of the project’s direct files. We just need to put this JS file in index.html

Webpack configuration webpack. Config. Js

Const path =require('path') Module.exports ={entry:'./ SRC /main.js', output:{// path.resolve() concatenate path, Resolve (__dirname,'dist'), filename:'bundle.js'}}Copy the code

(4) Partial installation of Webpack

Save-dev is a development-time dependency that does not need to be used after the project is packaged

NPM install [email protected] - save - dev

The webpack function is to pack out the package, only during the development phase, the packaging of the Webpack is uselessCopy the code

The script is defined here to execute the local Webpack first

As long as the terminal input webpack is using the global Webpack

(5) What is loader

Loader is a very core concept in Webpack

What is Webpack mainly used for?

In our previous example, we primarily used WebPack to process our JS code, and WebPack automatically handles dependencies between JS. However, in development, we don't just have basic JS code handling. We also need to load CSS, images also include some advanced es6 to ES5 code, SCSS, less to CSS, JSX,.vue files to JS files, etc. For WebPack itself, there is no support for these transitions so what? The webPack extension corresponds to the LoaderCopy the code

Loader Usage Process

Step 1: Install the loader using NPM. Step 2: Configure the loader in modules of webpack.config.jsCopy the code

Most of the loaders can be seen on webpack’s official website

(6) Process the LOADER of the CSS

File loading must rely on CSS-loader and style-loader. Css-loader only loads CSS files, and style-loader adds styles to the DOM. If you rely on the two loaders, use CSS-loader first and then style-loader. Use: [“style-loader”,”css-loader”]

(7) Webpack-less file processing

If we want to use less\ SCSS \stylus to write styles in a project, what about webpack?

npm install less [email protected] –save-dev

(8) Webpack – Image file processing

npm install url-loader --save-dev
Copy the code

When a loaded image is less than limit, the image is compiled as a Base64 string.

If the value is greater than limit, file-loader must be loaded. However, when it is larger than the image, it still generates an error. The main thing is that when we pack again, there is an image file in the dist folder. When we have this image, we find that the image is not displayed because the path of the image is not written correctly.

  • By default, WebPack returns the generated path directly to the consumer

  • However, our entire program is packaged in the dist folder, so we need to add a dist/ to the path, so we add publicPath:’dist/’ to output.

  • We noticed that the images in the Dist package were named with a 32-bit hash value to prevent duplication

If we name the image relative to it, we can set the name as follows:

(8) Webpack-ES6 syntax processing

If you read the webpack js file carefully, you will find that the ES6 syntax is not translated into ES5, and parts of it are unreadable by the browser.

Babel transforms ES6 into ES5

Babel is also a loader

(9) Webpack configures vUE

Since we will need to use VUE later in the actual project, it is not a development-time dependency

  • Step 1: Install vUE

npm i vue --save

  • Step 2: Import vUE,

import Vue from 'vue'

Create vUE instance objects

If the page displays nothing and no errors are reported, you can set it, and then NPM run dev

An error was detected during the package run, so we specify alias to specify which VUE we are currently using

(10) Difference between EL and template

Our future projects may have only one index.html, but we generally don’t change index.html.If we want to display content in index, we can write it in template

The vUE internally replaces template with where the EL was previously mounted

We have both el and template, and template replaces el and the nice thing about that is we don’t have to change anything in index.html

(11) VUE ultimate solution

Reconstruction (1)

Reconstruction (2)

Reconstruction (3)

Error because there is no corresponding loader and VUe-template-compiler

Installing vue-Loader and vue-template-Compiler are both development-time dependencies

NPM install [email protected] [email protected] --save-dev

See vue-loader.vuejs.org/zh/guide/#v…

At this point. Vue has compiled normally.

Resolve a path problem!

(12) know the plugin

* Plugins in Webpack are extensions to existing features of Webpack, such as packaging optimization and file compressionCopy the code

Loader is different from plugin

* Loader is mainly used to convert certain types of modules. It is a converter. * Plugin is an extension to Webpack itself, which is an extenderCopy the code

How to use plugin:

Step 2: Configure the plugins in the plugin in webpack.config.jsCopy the code

1. Add a Plugin for copyright

The plugin is called BannerPlugin and comes with WebPackCopy the code

(12) The use of webpack-htmlWebpackPlugin

Currently, our index.html file is stored in the root directory of the project

* We know that when we officially publish the project, we will publish the contents in dist folder, but if there is no index.html file in dist folder, then the js and other files will be meaningless. * Therefore, we need to package the index.html file into dist. At this point, you need to use the HtmlWebpackPluginCopy the code

What can HtmlWebpackPlugin do for us?

* Automatically generates an index. HTML file (you can specify a template to generate it) * inserts the packaged JS file into the body automatically with the script tagCopy the code

Install HtmlWebpackPlugin

  npm install html-webpack-plugin@3 --save-dev
  
  const HtmlWebpackPlugin=require('html-webpack-plugin')
  
  plugins: [
     new HtmlWebpackPlugin()
  ],
  
  
Copy the code

At this point, the package path is redundant

(12) the use of JS compression Plugin

Before our project is released, we must compress js files

* We use a third-party plugin uglifyjs-webpack-plugin with version 1.1.1. NPM install [email protected] --save-devCopy the code

Modify the webpack.config.js configuration file

   const UglifyjswebpackPlugin=require('uglifyjs-webpack-plugin')
   
    plugins: [ new UglifyjswebpackPlugin()],
   
Copy the code

(13) Webpack-dev-server builds the local server

Webpack allows you to build a local optional server based on Node.js and using the Express framework, which allows the browser to automatically refresh and display the results of your modifications

However, it is a separate module that needs to be installed NPM install –save-dev [email protected] before it can be used in webpack

9.Vue-Router

(1) Navigation guard

We introduced the navigation guard by modifying the page title case.

  • Common modification methods:

Mounted can be used to declare periodic functions in the VUE component corresponding to each route and execute corresponding codes to modify the route. However, it is inconvenient to maintain the route when there are too many pages.

  • Navigation Guard solves:

BeforeEach is a function that requires the function passed in as an argument when jumping from one route to another. The function passed in has 3 arguments, from, to, next, and next must be called. BeforeEach is executed when you jump from one route to another. Then we can define meta and metadata (data describing data) in the route. We can get meta dynamically through RO, but we can’t get meta if the route has nesting, so we can directly get the first element matched.

The first home has route nesting, and there is no title in meta, we can find it in matched

Router.beforeeach (function(to,from,next){console.log("to",to) // Jump from from to to document.title=to.meta. Title next()})Copy the code

transform

Router.beforeeach (function(to,from,next){console.log("to",to) // Jump from from to to // document.title=to.meta.title document.title=to.matched[0].meta.title next() })Copy the code

(2) Navigation guard replenishment

BeforeEach () is a front hook and must be called next() afterEach() is a post hook and does not actively call next()

Router.beforeeach (function(to,from,next){console.log("to",to) // Jump from from to to // document.title=to.meta.title Document.title =to.matched[0].meta. Title next()} Don't need to take the initiative to call next () function. The router afterEach ((to and from) = > {the console. The log (" + + + + + ", to the from)})Copy the code

Here we use the navigation guard, which we call the global guard

  • Route exclusive guard
  • Guards within components

(3) Route exclusive guard

You can define beforeEnter guards directly on the routing configuration

{ path:'/about', component:()=>import('.. /components/About'), meta:{title:' About'}, BeforeEnter: ((the to, from, next) = > {the console. The log (" routing exclusive guard -- -- -- -- ", to, from), next ()})},Copy the code

(4) VUE life cycle

(5) keep alive

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering

Router-view is also a component. If it is wrapped directly in keep-alive, all components matched by the path will be cached

When keep-alive is used, components are not created and destroyed frequently (some components can be excluded), and excluded components are still created and destroyed frequently

<keep-alive exclude="Profile,User">
    <router-view></router-view>
</keep-alive>
Copy the code
 created(){
    console.log("created")
  },
  destroyed(){
    console.log("destroyed")
  },
Copy the code
5.1 supplement
// Only this component is saved, Check that the value of activated(){console.log("aaa") this.$route.push (this.path)}, deactivated(){ console.log('deactivated') },Copy the code