At the forefront of

Out of the world just to observe!! I am Nezha. Re-study and consolidate your Vuejs knowledge system. If you miss any knowledge points, please explain them in the comments so that I can update the content knowledge system in time. Welcome to like collection!

The life cycle

First of all: New Vue(),new Vue(),new Vue instance, Observe data, init Events bind event, created create method, check whether there is an EL attribute, if not, vm.$mount(el) You can call this method manually to mount it. Determines whether there is a template attribute.

If there is an EL attribute, check whether there is a template attribute.

Instantiation and load life cycle functions during creation: beforeCreate and Created, beforeMount and Mounted.

BeforeCreate is called after the instance is initialized and before the data observer and event/ Watcher events are configured.

Update period

Run-time lifecycle functions: beforeUpdate and updated

Created instance is called after the created instance has been created.

The instance has completed the following configurations: data observer, property and method operations, and Watch/Event event callbacks.

The mount phase has not yet started and the $EL attribute is not currently visible.

BeforeMount is called before the mount begins and the associated render function is called for the first time. Mounted, vm.$el Is mounted in the document. Operations on existing DOM nodes can be performed during the file. BeforeUpdate Called when data is updated, which occurs before the virtual DMO is re-rendered and patched. Updated When this hook is called, the component DOM is updated, so you can now perform DOM-dependent operations. Activated, deactivated, beforeDestroy, destroyed. Called before instance destruction and after vue instance destruction.

Unloading phase

Life cycle functions during destruction: beforeDestroy and Destroyed

Instance lifecycle hooks

Each vUE instance goes through a series of initialization procedures when it is created, including setting up data listeners, compiling templates, mounting the instance to the DOM and updating the DOM as data changes, as well as running some functions called lifecycle hooks.

Used to give users the opportunity to add their own code at different stages.

BeforeCreate, in which case the data is not visible

data() { return { a: 1 } }, beforeCreate() { // red console.log(this.a); // not visible}Copy the code

A created instance is called after it has been created, at which point you can’t see the content of your page. The instance is complete with representations: data observer, property and method operations, watch/ Event event callbacks.

The mount phase has not yet started, and the $EL attribute is not currently visible.

export default { data() { return { a: 1 } }, beforeCreate() { console.log(this.a); }, created() { // red console.log(this.a); console.log(this.$el); $this.$el {}}Copy the code

BeforeMount is called before the mount begins and the associated render function is called for the first time.

export default{ data() { return { a: 1 } }, beforeCreate() { console.log(this.a); }, created() {console.log(this.a); console.log(this.$el); // Invisible}, beforeMount() {console.log(this.$el); // Not visible}}Copy the code

Mounted:

export default { data() { return { a: 1 } }, mounted() { console.log(this.$el); $el {$el}}Copy the code

BeforeUpdate hook, called before DOM updates:

beforeUpdate() {
    console.log(this.a);
}

// document.getElementById("web").innerHTML
Copy the code

Updated hook, called after DOM updates:

updated() {
    console.log(this.a);
}

// document.getElementById("web").innerHTML
Copy the code

Activated and deactivated (components)

Activated () {console.log(" component used "); }, deactivated() {console.log(" component disabled "); Data to Drag},Copy the code

Keep-alive is a built-in component of Vue that keeps state in memory during component switching, preventing repeated dom rendering.


when wrapping dynamic components, inactive component instances are cached rather than destroyed. Like
,

is an abstract component: it does not render a DOM element on its own, nor does it appear in the parent component chain.

When a component is switched within

, its activated and deactivated lifecycle hook functions are specified accordingly.

It is used because we do not want components to be re-rendered to affect the experience, or performance, to avoid performance degradation by multiple renderings. Cache it and maintain the current state.

Scene:

  1. Product list page Click the product to jump to the details of the product, the original information will still be displayed after the return
  2. Order list jumps to order details, returns, and so on.

Keep-alive lifecycle:

Created > Mounted > activated; Deactivated is triggered after exit. Re-enter: Activated is triggered. Mount methods, etc., that are executed only once in Mounted. The method that the component executes each time it goes in is placed in Activated.

App.vue parent component:

<template> <div> <button @click="myBtn"> myBtn </button> <keep-alive> <range v-if="isShow"></range> </keep-alive> </div>  </template> <script> import range from './components/range.vue' export default { data() { return { a: 1, isShow: true } }, methods: { myBtn() { this.isShow = ! this.isShow } }, components: { range } } </script>Copy the code

BeforeDestroy and destroyed

BeeforeDestroy is of type function, detailed: called before the instance is destroyed; at this step, the instance is still fully available.

This hook is not called during server-side rendering.

Destroyed is called after the vue instance is destroyed. All items indicated by the vue instance are unbound, all event listeners are removed, and all subinstances are destroyed.

This hook is not called during server-side rendering.

BeforeRouteEnter and beforeRouteLeave

beforeRouteEnter() {
    console.log('beforeRouteEnter')
},

beforeRouteLeave() {
    console.log('beforeRouteLeave')
}
Copy the code

Used by vUE routing, added when routing in and routing out.

Created () {console.log(' start executing a created hook function ') // Get data console.log(' get a created attribute '+this.value) // Get a page element Console. log(this.$refs['example']) this.$nextTick(()=>{console.log(' Create this.$nextTick() ')})}, $refs['example'].innertext () {console.log(' get mounted data '-- +this.$refs['example'].innertext) This.$nextTick(()=>{console.log(' Mounted ')})}, methods: UpdateDate (){}, Console. log(this.$refs['example'].innertext) this.$nextTick(()=>{get(){this.value=' update data '; console.log(this.$refs['example'].innerText) }) } }Copy the code

Var VM =new Vue({}) init events&LiftCycle =new Vue({}) init events&LiftCycle =new Vue({}) When the beforeCreate life cycle function executes, the data in data and methods are not initialized. In Created, data and methods are already initialized, so if you want to call methods in methods or manipulate data in data, you can only do it in Created. Vue then starts editing the template, executing the instructions in the Vue code, and eventually generates a compiled final template string in memory, rendering it into the DOM in memory, rendering the template in memory, without mounting the template to the actual page. BeforeMount is executed when the template is already compiled in memory but not yet mounted to the page. Create vm.$el and replace ‘el’ with it this step is to actually replace the template compiled in memory with the browser page. Mounted: After mounted is executed, the vue instance is initialized. At this point, the component moves from the creation phase to the run phase.

BeforeUpdate executes when the data displayed on the page is still old while the data data is up to date and the page has not been synchronized with the latest data. Updated event executes when the page and data are in sync and are new. Virtual DOM re-render and patch execution, first according to the latest data in the data, in memory, re-render a latest memory DOM tree, when the latest memory DOM tree is updated, it will re-render the latest memory DOM tree to the real page. Complete data update from data to view.

BeforeDestroy when the hook function executes, the Vue instance moves from run to destroy. At this point, the instance is still available and the destruction process is not actually performed. The component is completely destroyed and is no longer available when the destroyed function is executed.

Vue interview questions

Talk about your rightmvvmThe understanding of the

The process of bidirectional binding

View, route-controller Controller, data Model

View -> DOM, viewModel, Model data

In traditional MVC, a user operation would request a server-side route, which would call the corresponding controller for processing. The controller would get the data and return the results to the front end for the page to be re-rendered.

MVVM, for the traditional front end will manually render data to the page, MVVM mode does not require the user to receive the dom element manipulation, data binding to the viewModel layer, will automatically render data to the page, view changes will notify the viewModel layer to update data.

Vue responsive principle

  1. vueHow is it monitored internallymessageChanges in data
  2. When the data changes,vueHow do YOU know who to notify when a refresh occurs

Core:

  • Object.definePropertyListen for changes in object properties
  • Publish the subscriber model

Code:

Object.keys(obj).forEach(key => { let value = obj[key] Object.defineProperty(obj, key, {set(newValue) {// Listen to change value = newValue}, get() {return value}})}) obj.name = 'web'Copy the code

Publisher Subscriber

class Dep { constructor() { this.subs = [] } } class Watcher { constructor(name) { this.name = name; }}Copy the code

Get and set methods in accessor properties in object.defindeProperty of the Object

  • Convert the data togetterandsetter, to establishwatcherAnd collect dependencies.

Description:

Watcher updates the view with a callback function; The Observer observes data, notifying DEP to collect watcher through GET, notifying Watcher of data updates through notify(), and watcher collects dependencies through addDep().

Observer: used to listen for directives that hijack all data attributes, dep,watcher,view, Compile parse EL templates.

Follow the following figure (see vue.js)

We start by initializing data, using an Observer to listen for data, adding a Dep for each data attribute, and having two getters and setters for data. Add collect dependency operations in its getter procedure and notify dependency operations in setter procedure.

Generate the corresponding Watcher and collect the dependencies when parsing the instruction or setting the watch option to the Vue instance or calling $watch.

Data is converted into getters/setters through the Observer to track changes to the Data.

When the value of an object is changed, the corresponding setter is triggered, and the setter notifys each Watcher in the previously dependent collection Dep that the value has changed and the view needs to be rerendered.

Principle of data bidirectional binding

What is the principle of responsiveness

  1. Core:Object.defineProperty
  2. The defaultvueWhen the data is initialized, it givesdataAttribute use inObject.definePropertyRedefine all attributes. When the page gets the corresponding attribute, dependency collection will be carried out. If the attribute changes, relevant dependencies will be notified to update the operation.

InitData initializes the data passed in by the user, the new Observer observes the data, this.walk(value) processes the Object, defineReactive loops through Object properties to define responsive changes, Object.defineProperty, Redefine data using Object.defineProperty.

Redefine each item of data using Object.defineProperty.

Object.defineProperty(obj,key,{ enumerable: true, configurable: true, get: function reactiveGetter(){ const value=getter?getter.call(obj):val if(Dep.target){ dep.depend() if(childOb){ childOb.dep.depend() if(Array.isArray(value)){ dependArray(value) } } } return value }, set: function reactiveSetter(newVal) { const value=getter?getter.call(obj).val if(newVal === value || (newVal ! == newVal && value ! ==value)){ return } if(process.env.NODE_ENV ! == 'production' && customSetter){ customSetter() } val = newVal childOb = ! shallow && observe(newVal) dep.notify() } })Copy the code

How does Vue Chinese detect array changes

Using function hijacking to rewrite the array method, Vue rewrites the array prototype chain in Data, pointing to the array prototype method defined by itself, so that when the array API is called, it can notify the dependency update, if the array contains reference type, the reference type in the array will be monitored again.

InitData initializes the data data passed in by the user, new Observer makes observations of the data, protoAugment(value,arrayMethods) points the prototype method of the data to the overwritten prototype.

  • Rewrite the prototype method for arrays
  • observerArrayLook deeply at each item in the array

Code:

If (array.isarray (value)){// Evaluate Array if(hasProto){protoAugment(value, ArrayMethods) / / rewrite array prototype method} else {copyAugment (value, arrayMethods arrayKeys)} this. ObserveArray (value) / / depth to observe each item in the array }else{this.walk(value) // redefine object type data} function protoAugment(target, SRC: Object){ target.__proto__ = src } export const arrayMethods = Object.create(arrayProto) const methodsToPatch=[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] methodsToPatch.forEach(function (method){ const original = arrayProto[method] def(arrayMethods, method, function mutator(... args){ const result = original.apply(this.args) const ob = this.__ob__ let inserted switch(method) { case 'push': case 'unshift': inserted = args break case 'splice': Inserted = args.slice(2) break} if(inserted) ob.observerArray(inserted) // Observe the inserted data again ob.dep.notify() // notify a view update return result } } observeArray(items: Array<any>) { for(let i=0, l = items.length; i<1; I ++) {observe(item[I])}}Copy the code

Why does VUE use asynchronous rendering

If asynchronous updates are not used, the current component is re-rendered each time the data is updated, for performance reasons.

Dep.notify () notifies watcher to update, subs[I].update() calls watcher’s update, queueWatcher resends watcher to queue, and subs[I].update() calls watcher’s update. NextTick (flushSchedulerQueue) Asynchronously clears the Watcher queue.

Implementation principle of nextTick

Micro tasks are executed before macro tasks

The nextTick method mainly uses macro tasks and micro tasks, and defines an asynchronous method. Multiple calls to nextTick will queue the method, and the current queue will be cleared by this asynchronous method.

The nextTick method is asynchronous.

Callbacks. Push (cb) stores the callback into an array. TimerFunc () calls timerFunc and returns a Promise.

webpack

What is Webpack? Webpack is a static module packaging tool for modern JavaScript applications.

Webpack is a front-end modular packaging tool

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

Global installation

NPM install [email protected] - gCopy the code

Local installation

NPM install [email protected] - save - devCopy the code

Webpack.config.js fixed name file:

const path = require("path")
module.exports = {
    entry: './src/main.js',
    output: {
        patch: './dist',
        filename: ''
    },
}
Copy the code

package.json

{" name ": 'meetwebpack'," version ":" 1.0.0 ", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo..." }, "author": "", "license": "ISC" }Copy the code

What is the loader

Loader is a very core concept in Webpack

Loader usage process:

  1. throughnpmRequired for installationloader
  2. inwebpack.config.jsIn themoudulesKeyword to configure

Define startup in package.json

{" name ":" meetwebpack ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" build ": "Webpack}", "author" : ""," license ":" ISC ", "devDependencies" : {" webpack ":" ^ 3.6.0 "}}Copy the code

webpackThe introduction of

Webpack can be thought of as a module packer. It analyzes the structure of your project, finds JavaScript modules and other extensions that browsers don’t run directly, and packages them into a format that browsers can use.

Can realize code conversion, file optimization, code segmentation, module merge, automatic refresh, code check, automatic release.

Install the local Webpack

webpack webpack-cli -D
Copy the code

Initialization:

yarn init -y
Copy the code
yarn add webpack webpack-cli -D
Copy the code

Webpack can be configured to 0, it is a packaging tool, can output the result (Js module), packaging (support for Js modularization)

Run the webpack command to pack

npx webpack
Copy the code

Webpack. Config. js, webpack is written from node:

let path = require('path') console.log(path.resolve('dist'); Module. exports = {mode: 'development', // exports = {mode: 'production ', 'development entry ', // exports = {mode:' production ', 'development entry ', // exports: {filename: Resolve (__dirname, 'build'), // change relative path to absolute path}}Copy the code

Custom, webpack.config.my.js

Use the following command:

npx webpack --config webpack.config.my.js
Copy the code

package.json:

{" name ":" webpack dev - 1 ', "version" : "1.0.0", "main" : "index. Js", "license" : "MIT", "scripts" : {" build ": "Webpack --config webpack.config.my.js"}, "devDependencies": {"webpack": "^4.28.3", "webpack-cli": "^3.2.0"}Copy the code

Use the following command:

npm run build

// npm run build -- --config webpack.config.my.js
Copy the code

Develop the configuration of the server

Code:

let path = require('path') let HtmlWebpackPlugin = require('html-webpack-plugin') console.log(path.resolve('dist'); Module. exports = {devServer: {// devServer configuration port: 3000, // see progress: true, contentBase: "./build", compress: True}, mode: 'development', // default two types, production, development entry: '' // entry output: {filename: Resolve (__dirname, 'build'), // rewrite relative paths to absolute paths}, plugins: New HtmlWebpackPlugin({template: './ SRC /index.html', filename: 'index.html', minify:{removeAttributeQuotes: true,// delete "" collapseWhitespace: true,// collapse)], module: collapseWhitespace: true {// module rules: [// rules {test: /\.css$/, use: [{loader: 'style-loader', options: {insertAt: 'top' } },'css-loader'] }, ] } }Copy the code
Output: {filename: 'bundle.[hash:8].js',// only 8 bits are displayed after packing the filename}Copy the code
{" name ":" webpack dev - 1 ', "version" : "1.0.0", "main" : "index. Js", "license" : "MIT", "scripts" : {" build ": "webpack --config webpack.config.my.js", "dev": "webpack-dev-server" }, "devDependencies": { "webpack": "^4.28.3", "webpack-cli": "^3.2.0"}}Copy the code
yarn add css-loader style-loader -D
Copy the code

Style:

  1. style-loaderAdds the export of the module as a style todomIn the
  2. css-loaderparsingcssFile after useimportLoad, and returncsscode
  3. less-loaderLoad and translatelessfile
  4. sass-loaderLoad and translatesass/scssfile
  5. postcss-loaderusePostCSSLoad and translatecss/sssfile
  6. stylus-loaderLoad and translateStylusfile

Style – loader installation:

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

Usage:

You are advised to use style-loader and CSS-loader together

component.js

import style from './file.css'
Copy the code
  1. css-loaderOnly load the CSS file
  2. style-loaderIs responsible for adding styles todomIn the
  3. The use of multipleloaderIs from right to left

Code:

// webpack.config.js
module: {
    rules: [
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
        }
    ]
}
Copy the code

CSS file processing: style-loader

Install style – loader

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

Style-loader must be placed in front of CSS-loader. Webpack reads loaders from right to left.

The configuration of webpack.config.js is as follows:

Const path = require('path') module.exports = {// entry: string/array/object. Entry: './ SRC /main.js', // exit: Usually an object containing at least two important attributes, path and filename output:{path: Path.resolve (__dirname, 'dist'), // Note: path is usually an absolute path filename: 'bundle.js'}, module: {rules: {{test: /\.css$/, use: ['style-loader','css-loader'] } } } }Copy the code

webpackLess File processing

Installation:

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

Example:

A chain call of CSS-loader,style-loader, and less-loader can apply all styles to the DOM at once.

// webpack.config.js
module.exports = {
    ...
    rules: [{
        test: /\.less$/,
        use: [{
            loader: 'style-loader'
        },{
            loader: 'css-loader'
        },{
            loader: 'less-loader'
        }]
    }]
}
Copy the code

Image file processing

CSS Normal code:

body { background: url(".. /img/test.jpg") }Copy the code

url-loader

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

usage

The url-loader function is similar to file-loader, but returns a DataURL if the file size is below the specified limit

import img from './image.png'
Copy the code

webpack.config.js

module.exports = { module: { rules: [ { test: /\.(png|jpg|gif)$/, use: [ { loader: 'url-loader', options: { limit: 8192}}]}}Copy the code

Img, the folder to which files are packed

Name, gets the original name of the image, in this position

Hash :8. To prevent image name conflicts, we still use hash, but we only keep 8 bits

Ext, using the original extension of the image

Es6 to ES5 Babel

If you want to convert ES6 to ES5, you need to use Babel

npm install --save-dev babel-loader@7 babel-core babel-preset-es2015
Copy the code

To configure the webpack.config.js file:

{ test: /\.m? js$/, use: { loader: 'babel-loader', options: { presets: ['es2015'] } } }Copy the code

Using the vue

How to integrate vue.js in our Webpack environment

Code:

npm install vue --save
Copy the code
  1. runtime-onlyYou can’t have any in your codetemplate
  2. runtime-compilerIn your code, you can havetemplateBecause there arecompilerCan be used for compilationtemplate

Spa (Simple Age Web Application)-> Vue-Router

. Vue file encapsulation

Install vue-loader and vue-template-Compiler

npm install vue-loader vue-template-compiler --save-dev
Copy the code

Learn about the WebPack plugin

  1. pluginWhat is?
  • pluginPlug-in means plug-in, usually used to extend an existing architecture.
  • webpackPlugins, yeswebpackVarious extensions to existing functionality.
  1. loaderandpluginThe difference between
  • loaderPrimarily used to convert certain types of modules, it is a converter.
  • pluginIt’s a plug-in. It’s rightwebpackThe extension itself is an extender.
  1. pluginThe process of using:
  • throughnpmRequired for installationplugins
  • inwebpack.config.jsIn thepluginsConfigure plug-ins in

Webpack.config.js file:

Check the header of the bundle.js file:

Vue Cli,

What is vue CLI, Command Line Interface, commonly known as scaffolding, vue CLI is an official release project scaffolding. Vue-cli can be used to quickly set up a VUE development environment and the corresponding Webpack configuration.

Vue CLI

Install VUE scaffolding

npm install -g @vue/cli
Copy the code

Vuecli2 initialization process

Code:

vue init webpack vuecli2test
Copy the code
  1. Create a folder based on the name and store the contents of the subsequent project. This name will be used as the default project name, but cannot contain uppercase letters, etc
  2. Project nameProject name, cannot contain uppercase
  3. Project descriptionProject description
  4. AuthorThe author information
  5. Vue build``runtime
  6. Install vue-router``noWhether to install

Directory structure details

Build config is webpack-specific,node_modules is node-related, and SRC is where the code is written. .babelrc is es code specific transformation configuration,.editorConfig project text specific configuration,.gitignore “” git repository ignored folder configuration,.postcssrc.js is CSS specific transformation configuration.

.editorconfig

Front-end modular:

Why use modularization, simple writing JS code brings problems, closures cause code can not be reused, self-implementation of simple modularization, modular use in ES: export and import.

npm install @vue/cli -g
Copy the code
npm clean cache -force
Copy the code

Vue CLI2 initialization:

vue init webpack my-project
Copy the code

Vue CLI3 initialization project:

vue create my-project
Copy the code

The use of arrow functions and this

Arrow functions are just a way of defining functions

  1. How to define a function:function
const a = function(){
    
}
Copy the code
  1. Object literals that define functions
const obj = {
    b: function() {
        
    },
    b() {
        
    }
}
Copy the code
  1. Arrow function
Const c = (parameter list) => {} const c = () => {}Copy the code

Arrow function arguments and return values

Code:

const sum = (num1, num2) => {
    return num1 + num2
}

const power = (num) => {
    return num * num
}

const num = (num1,num2) => num1 + num2
Copy the code
const obj = { a() { setTimeout(function() { console.log(this); // window }) setTimeout(()=>{ console.log(this); // obj object})}}Copy the code

Vue-router is basically used for routing, vue-router nested routines are passed by vue-router parameter, vue-router navigation guard.

Routing is a network engineering term. Routing is the activity of transmitting information from a source address to a destination address over an interconnected network.

Routers provide two mechanisms: routing and forwarding. Routing determines the path of a packet from its source to its destination, and forwarding transfers data from the input to the appropriate output. There is a very important concept in routing called routing table. A routing table is essentially a mapping table that determines the direction of packets.

Back-end routing: The back-end handles the mapping between urls and pages.

Front-end and back-end routing, front-end and back-end rendering

The difference between vue-router and KOa-router:

Vue-router is a front-end route, and KOA-router is a back-end route.

Vue-router Front-end routing principles:

Front-end routing modes include hash mode and history mode.

The concept of routing comes from the server, where routing describes the mapping between urls and processing functions.

Front and back end render wars

In the urlhashandhtml5thehistory

The core of front-end routing is to change the URL, but not refresh the page as a whole. In fact, the most important feature of SPA is to add a layer of front-end routing on the basis of the separation of front and back ends. It’s the front end that maintains a set of rules.

The url hash

The HASH of the URL is the anchor point #, which essentially changes the href attribute of window.location. The location. Hash value is directly assigned to change the href, but the page is not refreshed.

Html5 history mode: pushState

Html5 history mode: replaceState

Html5 history mode: Go

history.go()

History.back () is equivalent to history.go(-1)

History.forward () is equivalent to history.go(1)

Install the vue – the router

npm install vue-router --save
Copy the code
  1. Import the route object and callVue.use(VueRouter)
  2. Create a route instance and pass in the route mapping configuration
  3. inVueInstance to mount the created routing instance

Code:

Import VueRouter from 'vue-router' import vue from 'vue' import Home from '.. /components/Home' import About from '.. Use (VueRouter) // Const routes = [{path: '/home', component: Home }, { path: '/about', component: Const VueRouter = new VueRouter({routes}) // Pass router to export default RouterCopy the code

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
 el: '#app',
 router,
 render: h => h(App)
})
Copy the code

Steps to use vue-router

  1. Creating a Routing Component
  2. Configuring route mapping: Component and path mapping
  3. Using route: Pass<router-link>and<router-view>

Code:

Component components

// home <template> <div> <h2> </template> <script> export default {name: 'Home' } </script> <style scoped> </style>Copy the code
</h2> </div> </template> <script> export default {name: 'Aboout' } </script> <style scoped> </style>Copy the code

App.vue

<template> <div id="app"> <router-link to="/home"> </router-link> <router-view></router-view> </div> </div> <script> export default { name: 'App' } </script> <style> </style>Copy the code

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
 el: '#app',
 router,
 render: h => h(App)
})
Copy the code

Route accidental value and change to history mode

Creating a Router Instance

Code:

router->index.js

Import Vue from 'Vue' import VueRouter from 'vue-router' import VueRouter from 'vue-router' import Vue. Use (VueRouter) const routes = [] // Const router = new VueRouter({routes}) // Export default RouterCopy the code

The main. Js code:

import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
 el: '#app',
 router,
 render: h=>h(App)
})
Copy the code

router->index.js

import Vue from 'vue' import VueRouter from 'vue-router' import Home from '.. /components/home' import About from '.. Use (VueRouter) // Const routes = [{path: '/home', Component: home}, {path: '/about', component: About } ]Copy the code

Use the app.vue code

<template> <div id="app"> <router-link to="/home"> </router-link> <router-view></router-view> </div> </template> <script> export default { name: 'App', components: { } }Copy the code
  1. <router-link>The label is avue-routerThe component is already built in and it will be rendered as one<a>The label
  2. <router-view>This TAB dynamically renders different components based on the current path.
  3. Other content of the page, such as the title or navigation at the top, or some version information at the bottom, etc<router-view>At the same level.
  4. During route switchover, the route is switched<router-view>Mounted components, other content does not change.

Default route path

By default, when you go to the home page of the site,

renders the contents of the home page, but the home page component is not displayed by default and must be clicked by the user.

How to make the path jump to the home page by default, and

render the home page component, just configure a mapping:

const routes = [
 {
     path: '/',
     redirect: '/home'
 }
]
Copy the code

Redirect = /home = /home = /home = /home = /home = /home = /home = /home = /home = /home = /home = /home = /home = /home

// main.js const router = new VueRouter({routes, mode: 'history'})Copy the code

Ways to change paths:

  1. urlthehash
  2. html5thehistory
  3. By default, path changes are usedurlthehash

Using HTML5’s History mode:

Const router = new VueRouter({routes, mode: 'history'})Copy the code

Router-link uses a property, to, to specify the path to jump to. The tag can specify what component is rendered after

.

The replace attribute does not leave a history record, and if replace is specified, the back key does not return to the previous page.

If the

route matches successfully, the system automatically sets a router-link-active class for the current element. You can change the default active-class name.

const router = new VueRouter({
 routes,
 mode: 'history',
 linkActiveClass: 'active'
})
Copy the code

Routing code jump

App. Vue code:

</button @click="linkToHome"> </button @click="linkToHome"> </button> <router-view></router-view> </div> </template> <script> export default { name: 'App', methods: { linkToHome() { this.$router.push('/home') }, linkToAbout() { this.$router.push('/about') } } } </script>Copy the code

<img: SRC ="imgURL" Alt =""> <router-link :to="'/uer/' + userId"> User </router-link> <script> export default {name: 'User', computed: { userId() { return this.$route.params.userId } } } </sript>Copy the code

const Home = () => import('.. /components/Home') const HomeNews = () => import('.. /components/HomeNews') const HomeMessage = () => import('.. /components/HomeMessage') { path: '/home', component: Home, children: [ { path: 'news', component: HomeNews }, { path: 'news', component: HomeMessage } ] }Copy the code
<router-link to = "/home/news"> News </router-link> <router-link to = "/home/message"> Information </router-link>Copy the code

Default:

The way parameters are passed

There are two main types of passing parameters, Params and Query

Types of params:

  1. Configure the routing mode:/router/:id
  2. Delivery mode: inpathThis is followed by the corresponding value
  3. The path formed after transmission:/router/123

Vue-router passes the parameter code

< the router - link: to = "{path: '/ profile'}" > user < / router - the link >Copy the code

Uniform resource locator

Uniform resource Locator, uniform resource locator, uniform resource locator address, Url address, etc., web address. The address of a standard resource on the Internet, like a house tag on a network.

userClick() { this.$router.push('/user/' + this.userId) } btnClick() { this.$router.push({ path: '/user', query: {name: 'web', age: 12, height: 1.2}})}Copy the code

$route is different from $router

The parameter is obtained via the $route object. In applications using vue-Router, the route object is injected into each component with the value this.$route and is updated when the route is switched.

<template>
 <div>
  <p> {{$route.params}} </p>
 </div>
</template>
Copy the code

The type of query:

  1. Configure the route format:/routerAlso common configuration
  2. Pass mode, used in objectsquerythekeyAs a means of delivery
  3. The path formed after transmission,router? id=123./router? id=abc

$route is different from $router

const router = new VueRouter({
 routes,
 mode: 'history',
 linkActiveClass: 'active'
})
Copy the code

Vue.config.productionTip = false

Vue.prototype.test = function() {
    console.log('test')
}

Vue.prototype.name  = 'web'
Copy the code

$route is different from $router

  1. $routerforVueRouterInstance that wants to navigate to differenturl, use the$router.pushMethods.
  2. $routeFor the currentrouterYou can get it from the jump objectname.path.query.paramsAnd so on.

Vue-router Indicates global navigation

Meta: metadata

Router. BeforeEach ((to,from,next) => {// From jump to document.title = to.matched[0].meta. Title console.log(to); next() })Copy the code
AfterEach ((to,from) => {console.log(); })Copy the code

Navigation Guard: Navigation indicates that the route is changing.

Vue-router provides navigation guards that are used to guard navigation by jumping or canceling. There are multiple opportunities for routing navigation, global, single route proprietary, or component-level.

Global guard

You can register a global front-guard using router.beforeEach:

const router = new VueRouter({.. }) router.beforeEach((to,from,nex)=>{ })Copy the code

When a navigation is triggered, the global front-guard is called in the order it was created. The guard resolves asynchronously, in which case the navigation waits until all the guards resolve.

  1. to:Route, the destination route object to be entered
  2. from:Route, the current navigation is about to leave the route
  3. next:Function, be sure to call this methodresolveThis hook.

vue-router-keep-alive

Keep alive and vue — the router

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

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

Properties:

  1. includeString or regular expression, only matching components are cached
  2. excludeStrings or regular expressions, and any matching components are not cached
<keep-alive> <router-view> // All view components matched by the path will be cached </router-view> <keep-alive>Copy the code

PromiseThe use of

Es6 features Promise, which is a solution for asynchronous programming.

Timer asynchronous events:

setTimeout(function() {
    let data = 'web'
    console.log(content)
},1000)

new Promise((resolve, reject) => {
    setTimeout(function(){
        resolve('web')
        reject('error')
    },1000)
}).then(data=>{
    console.log(data)
}).catch(error=> {
    console.log(error)
})
Copy the code

Promise has three states:

  1. pendingWait state, such as network request in progress or timer out of time.
  2. fulfill, meet the status, active callbackresolve, and the callback.then()
  3. rejectReject state, callbackreject, and the callback.catch()

Vuex,

Vuex is a state management mode developed specifically for vue.js applications

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

  1. Status management mode
  2. Centralized storage management

Mutations (commit) -> State -> View ComponentsCopy the code

Vuex has five core concepts:

State, Getters, Mutation, Action, Module

State Single State tree, single data source.

Mutation status update

Vuex store update only way, submit Mutation

Mutation mainly includes two parts:

  1. The event type of a string
  2. A callback function whose first argument isstate

Mutation definition:

mutations: {
    increment(state) {
        state.count++
    }
}
Copy the code

Update by mutation

increment: function() {
    this.$store.commit('increment')
}
Copy the code

The parameter is called the payload of mutation

The state in Vuex’s store is responsive, and the Vue component updates automatically when the data in the state changes.

  1. In the earlystoreTo initialize the required properties
  2. tostateWhen adding a new attribute to the object in
  • useVue.set(obj,'newObj',123)
  • Assign a new object to an old object

Mutation constant type

// mutation-types.js export const UPDATE_INFO = 'UPDATE_INFO' import Vuex from 'vuex' import Vue from 'vue' import * as types from './mutation-types' Vue.use(Vuex) const store = new Vuex.Store({ state: { info: { name: 'web', age: 12 } }, mutations: { [types.UPDATE_INFO](state, payload) { state.info = {... state.info, 'height': payload.height } } })Copy the code
<script>
 import {UPDATE_INFO} from './store/mutation-types';
 export default{
     name: 'App',
     components: {
         
     },
     computed: {
         info(){
             return this.$store.state.info
         }
     },
     methods: {
         updateInfo(){
             this.$store.commit(UPDATE_INFO,{height:1.00})
         }
     }
 }
</script>
Copy the code

Note: do not perform asynchronous operations in mutation, mutation sync functions where methods must synchronize methods.

The basic definition of action, if there is an asynchronous operation, such as a network request,

Update (state) {setTimeout(()=>{state.info.name = 'web'},1000)} mutations: {// method [INCREMENT](state){state.counter++}}Copy the code
Actions: {// context: context, = store <! --aUpdateInfo(context) {--> <! -- setTimeout(()=>{--> <! -- state.info.name = 'web'--> <! -}, 1000) -- > <! -} -- >}Copy the code
actions: {
    aUpdateInfo(context) {
        setTimeout(()=>{
            context.commit('updateInfo')
        },1000)
    }
}

// xx.vue
updateInfo(){
    this.$store.dispatch('aUpdateInfo')
}
Copy the code

updateInfo(){ <! --this.$store.commit('updateInfo')--> this.$store.dispatch('aUpdateInfo',{ message: 'web', success: () => { console.log('web') } }) }Copy the code
aUpdateInfo(context, payload) {
    return new Promise((resolve, reject) => {...})
}
Copy the code

Modules in vuex

Modules means module

getters: {
    stu(){
        
    },
    stuLength(state, getters) {
        return getters.stu.length
    }
}
Copy the code

Using root data:

getters: {
    fullName(state) {
        return state.name + '1'
    },
    fullName1(state, getters) {
        return getters.fullName + '2'
    },
    fullName3(state, getters, rootState) {
        return getters.fullName2+rootState.counter
    }
}
Copy the code

Print console.log(context) in actions in the module

Actions receives a context parameter object, the local state is exposed through context.state, and the rootState is context.rootstate

import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import moduleA from './modules/moduleA'

import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)

const state = {
    
}

const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
    modules: {
        a: moduleA
    }
})

export default store
Copy the code

Network encapsulation

Encapsulation of axios network modules

Ajax is based on XMLHttpRequest(XHR); Jquery-ajax is much better than traditional Ajax.

Axios features:

  • Send it in the browserXMLHttpRequestsrequest
  • innode.jsSent inhttprequest
  • supportPromise API
  • Intercept requests and responses
  • Transform request and response data

Axios request:

axios(config)
axios.request(config)
axios.get()
axios.delete()
axios.head()
axios.post()
axios.put()
axios.patch()
Copy the code

The installation

npm install axios --save
Copy the code
Axios ({/ / by default the get url: "', method: 'get'}), then (res = > {the console. The log (res)})Copy the code
// import request from ".. /utils/request.js" import {request} from './network' export function getHome() { return request({ url: '/home/xxx' }) } export function getXX(type, page) { return request({ url: '/home/xx', params: { type, page } }) }Copy the code

Concurrent requests

Code:

axios.all([axios({ url: '' }), axios({ url: '', params: { type: '', page: 1, } })]).then(results => { }) // then(axios.spread((res1,res2)=>{... }))Copy the code

Global configuration

axios.defaults.baseURL='' axios.all .. { url: '/home' } axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; axios.defaults.baseURL = global.HOST;Copy the code

request.js

Import axios from 'axios' export function request(config,success,failure){const instance = axios.create({ BaseURL: ", timeout: 5000}) // Send network request instance(config). Then (res=>{success(res)}). Catch (err=>{failure(err)})}Copy the code

main.js

import {request} from './xx/request'

request({
    url: ''
},res=>{

),err=>{
    
}
Copy the code

You can also use the promise method, but the promise itself is returned

import axios from 'axios'
export function request(config) {
    const instance = axios.create({
        baseURL: '',
        timeout: 2000
    })
    return instance(config)
}
Copy the code

The use of axios interceptors

/ / configuration request and response to intercept the instance. The interceptors. Request. Use (config = > {the console. The log (' request interceptor in success) return the config}, err = > { The console. The log (' request interceptor in failure) return err}) instance. Interceptors. Response. Use (response = > { Console. log(' Response intercepting success ') return response.data},err => {console.log(' Response intercepting failure ') return err})Copy the code

Encapsulation axios

// request.js import axios from 'axios' cosnt service = axios.create({ baseURL: process.env.BASE_API, timeout: 2000}) service. Interceptors. Request. Use (config = > {/ / send the request before do some processing, data conversion, configuration request header, Config. data= json.stringify (config.data); config.headers = { 'Content-Type':'application/x-www-form-urlencoded' } return config },error=>{ Promise.reject(error) }) / / response interceptor service. The interceptors. Response. Use (response = > {return response}, Error => {if (error && error. Response) {switch (error.response.status) {case 400: error. Message = 'error request' break; Case 401: error. Message = 'unauthorized, please login again' break; Case 403: error. Message = 'access denied' break; Case 404: error.message = 'window.location.href = "/NotFound" break; Case 405: error. Message = 'request method not allowed' break; Case 408: error. Message = 'request timeout' break; Case 500: error. Message = 'server error' break; Case 501: error. Message = 'network not implemented' break; Case 502: error. Message = 'network error' break; Case 503: error. Message = 'service unavailable' break; Case 504: error. Message = 'network timeout' break; Case 505: error. Message = 'HTTP version does not support this request' break; default: Error. Message = 'connection error ${error.response.status}'}} else {if (json.stringify (error).includes('timeout')) { Message.error(' Server response timed out, Please refresh current page ')} error.message(' failed to connect to server ')} message.error (err.message) return promise.resolve (error.response)}) // import file export default serviceCopy the code

Encapsulate the request HTTP.js

import request from './request' const http ={ /** * methods: @param */ get(url,params){const config = {methods: 'get', url:url } if(params){ config.params = params } return request(config) }, post(url,params){ const config = { methods: 'post', url:url } if(params){ config.data = params } return request(config) }, put(url,params){ const config = { methods: 'put', url:url } if(params){ config.params = params } return request(config) }, delete(url,params){ const config = { methods: 'delete', url:url } if(params) { config.params = params } return request(config) } } export default httpCopy the code
// api.js import http from '.. /utils/ HTTP 'let resquest = "/xx/request/" // get export function getListAPI(params){return HTTP. Get (' ${resquest}/ getlist. json ',params)}, const service = axios. Create ({baseURL: process.env.BASE_API, timeout: 3 * 1000 })Copy the code

project

Create a project:

vue create webMall

npm run serve
Copy the code

// .editorconfig
root = true
[*]
charset = utf-8
indent_style=space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
Copy the code

The project is deployed under Window

The main. Js code:

import store from './store' import FastClick from 'fastclick' import VueLazyLoad from 'vue-lazyload' import toast from Prototype.$bus = new Vue() // Install toast plugin Fastclick. attach(document.body) // Use (VueLazyLoad,{loading: require('./xx.png') })Copy the code

Install nginx on Windows, deploy it on Linux, and install nginx on centos

linux ubuntu

Ubuntu is a desktop based Linux operating system whose name comes from the Zulu or Hausa word for Ubuntu in southern Africa.

Operating system: Windows 10 + Centos6.5 (vm)

yum install nginx
systemtl start nginx.service
systemctl enable nginx.service
Copy the code

Upload vUE project files to the cloud server through Xftp

Use Xshell to connect to the cloud server

The host is the public IP address of the instance created on Ali Cloud

Enter the login name and password. The login name is the one entered when you purchase the server.

Run the NPM run build command and there is a dist folder, which is the packaged vUE project file.

Nginx installation configuration

Enter the yum install nginx command on the Xshell terminal and press enter “y” to confirm.

After the installation is complete, enter service nginx start to start the nginx service.

Run the nginx -t command to view the nginx installation directory.

Run the CD /etc/nginx command to switch to the nginx directory, and then run cat nginx.conf to view the current nginx configuration file.

Type the command wget https://nodejs.org/dist/v10.8.0/node-v10.8.0-linux-x64.tar.xz enter, waiting for installation.

Enter tar XVF node-v10.8.0-linux-x64.tar.xz and press Enter to decompress the file.

Summary:

  1. The calculated property is called only once when used multiple times, because it is cached
  2. Decorator:stop.prevent..enter..once..native, etc.lazy.number.trimAnd so on.
  3. The classification of template writing method:script.template
  4. Communication between parent and child components: parent to child,propsSon to father,$emit
  5. The project,npm install.npm run serve
  6. webStormThe development ofvueinPluginsInstalling a plug-invue.js
  7. inserverVersion,VueA new uniform syntax was introduced for named slots and scoped slots (i.e<v-slot>Instructions). It has replaced theslotslot-scopeThese two features are currently deprecated, not yet removed, and still in documentation.
  8. v-slotUsage is divided into three categories: default slot, named slot, and scoped slot.

Scope slot, which accepts a set of properties passed in by a child component through the slot-scope property

  • The default slot

Code:

// Subcomponent <template> <div> <header> <slot> Default </slot> </header> </div> </template>Copy the code

Anything that is not wrapped in

// Parent component <template> <div> <child> content 1 <template> content 2</template> content 3 </child> <child V-slot =" Web "> slot <br> slot <br> </child> </div> </template>Copy the code
  • Named slot:v-slotDefine the same thing over and overnameOnly the contents of the last defined slot are loaded
// Subcomponent <template> <div> <main> <slot name="main"></slot> </main> <footer> <slot name="footer"></slot> </footer> </div> </template>Copy the code
  • Scope slot:
// Subcomponent <template> <div> <footer> <slot name="footer" :user="user" :testBtn="testBtn"> {{user.name}} </slot> </footer> </div> </template> <script> exportdefault { name: 'child', data () { return { user: { title: 'web', name: 'web' } }; }, methods:{ testBtn(){ alert('web'); }}}; </script>Copy the code

How does a Vue directly call methods in Component

<template>
  <div>
    <b-component ref="BComponent"></b-component>
  </div>
</template>
 
<script>
import BComponent from './BComponent'
 
export default {
  name: 'A',
 
  data () {
  },
 
  components: {
    BComponent
  },
 
  methods: {
    callACompoentFunction () {
      this.$refs.BComponent.sayHi()
    }
  }
}
</script>
 
<style scoped>
</style>
Copy the code
<template> <div></div> </template> <script> export default { name: 'B', data () { }, methods: { sayHi () { console.log('web! ') } } } </script> <style scoped> </style>Copy the code

The last

I am programmer Doraemon, Blue Fat man, excellent creator of Jian Shu Wan Fan, excellent author of Nuggets, EXPERT of CSDN blog, and active author of Cloud + community. I am committed to creating A series of high-quality articles that can help programmers improve. Website @ www.dadaqianduan.cn