Source: making stars ✨ | o | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author

axios

Axios is a Promise-based HTTP library that can be used in browsers and Node.js. Simply put, the front end is the most popular and simplest HTTP request solution.

function

  • Create XMLHttpRequests from the browser
  • Create HTTP requests from Node.js
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request data and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports XSRF defense

Code encapsulation

Toolclass encapsulation

// import axios from 'axios'; Const httpService = axios.create({// url prefix -'https://some-domain.com/api/' baseURL: Process.env.base_api, // need to customize // request timeout time: 3000 // need to customize}); / / request interceptor httpService. Interceptors. Request. Use (config = > {/ / according to the condition to join token - security carries the if (true) {/ / must be custom / / for each request carry a token config.headers['User-Token'] = ''; } return config; }, error => {// request error processing promise.reject (error); }) / / respone interceptor httpService. Interceptors. Response. Use (response = > {/ / unified handling state const res = response. The data; if (res.statuscode ! Reject ({status: res.statuscode, message: res.message}); return promise.reject ({status: res.statuscode, message: res.message}); } else { return response.data; 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 = 'error '; break; Case 405: error. Message = 'request method not allowed '; break; Case 408: error. Message = 'Request timed out '; break; Case 500: error. Message = '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 = 'unknown error ${error.response.status}'; }} else {error. Message = "Failed to connect to server "; } return Promise.reject(error); }) / /* * get * url: request * params: parameter * */ export function get(url, params = {}) { return new Promise((resolve, reject) => { httpService({ url: url, method: 'get', params: params }).then(response => { resolve(response); }).catch(error => { reject(error); }); }); } /* * export function post(url, params = {}) {return new Promise((resolve, resolve)) reject) => { httpService({ url: url, method: 'post', data: params }).then(response => { resolve(response); }).catch(error => { reject(error); }); }); } /* * export function fileUpload(url, params = {}) {return new Promise((resolve, resolve)) reject) => { httpService({ url: url, method: 'post', data: params, headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { resolve(response); }).catch(error => { reject(error); }); }); } export default { get, post, fileUpload }Copy the code

use

Import fetch from '@/util/fetch' // use const TMPURL = ''; // const params = {}; Fetch. Post (TMPURL + '/login/login', params);Copy the code

What is 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 an application and rules to ensure that the state changes in a predictable way. Install devTools extension for Chrome

Unidirectional data flow

Schematic illustration:

  • State: Data source (one-way data flow) that drives the application
  • View: map state declaratively to View (statically displayed data source)
  • Actions: Handle state changes caused by user Actions on the view (data source change tracking)

A simple demo example:

<template> <div> <! -- view --> <div>{{ count }}</div> <button @click="increment">increment</button> </div> </template> <script> export default { // state data () { return { count: 0 } }, // actions methods: { increment () { this.count++ } } } </script> <style> </style>Copy the code

Vuex solves the problem

  • State sharing between multiple view components, including parent and sibling components
  • The behavior of different view components needs to change the same state

Vuex application scenarios

Medium and large single-page applications need to consider how to better manage state outside the component. Simple applications are not recommended

Differences between VUEX and global variables

  • Reactive: VuEX’s state storage is reactive. When Vue components read state from store, if the state in Store changes, the corresponding components will be updated efficiently
  • The only way to change the state in a store is by committing mutation, which is convenient for tracking each state change

Vuex core process

Schematic illustration:

  1. Vue Components: Vue Components. On the HTML page, responsible for receiving user operations and other interactive behaviors, execute the Dispatch method to trigger corresponding actions to respond
  2. Dispatch: Action action trigger method, the only method that can execute an action
  3. Actions: Action handling module. Responsible for handling all interactions received by Vue Components. Contains synchronous/asynchronous operations and supports multiple methods of the same name that are triggered in the order of registration. Requests to the background API are made in this module, including triggering other actions and submitting mutations. This module provides the encapsulation of promises to support the chain firing of actions
  4. Commit: State changes Commit operation method. Committing for mutation is the only way to perform mutation
  5. Mutations open the door. Is the only recommended method for Vuex to modify state. Other modification methods will report errors in strict mode. This method can only perform synchronous operations, and the method name must be globally unique. Some hooks will be exposed during the operation for state monitoring and so on
  6. State: page State management container object. Centralized storage of scattered data objects in Vue Components, globally unique, for unified state management. The data required for page display is read from this object, leveraging Vue’s fine-grained data response mechanism for efficient status updates
  7. Getters: State Object reading method. This module is not listed separately and should be included in Render, where Vue Components read the global state object

Summary: After receiving the interaction behavior, the Vue component called the Dispatch method to trigger the relevant action processing. If the page state needed to be changed, it called the commit method to submit the mutation and modify the state, obtained the new state value through getters, and re-rendered the Vue Components. The interface is updated

The installation

npm install vuex --save
Copy the code

A simple example

SRC /vuex/store.js

Import vue from 'vue' import vuex from 'vuex' import vuex from 'vuex' import vuex from 'vuex' import vuex from 'vuex' import vuex from 'vuex' Const state = {// Place initial state count: 1} / / 2, mutations: create change the status of the const mutations = {/ / state function change - general capital ADD (state, n) {state. Count + = n; Const getters = {function(state){return state.count; } // 4, actions: Open mutations const actions ={open mutations const actions ={open mutations const actions ={open mutations add ({commit}, data) {commit (' add ', Data)}} const Store = new vuex. Store({state, mutations, getters, actions}); // 6, store export default store;Copy the code

Code description:

  • State-mutations – getters – actions – store, the above writing method is basically fixed.
  • Small projects use the simple administrative state above.

(2) SRC /main.js code

Import Vue from 'Vue' import App from './App' import router from './router' // import store import store from './vuex/store' Vue. Config. productionTip = false /* eslint-disable no-new */ new Vue({el: '#app', router, store, // global injection components: { App }, template: '<App/>' })Copy the code

SRC /compontent/ count.vue

< the template > < div class = "hello" > < h1 > {{MSG}} < / h1 > < h2 > {{count}} < / h2 > < button @ click = "clickAdd" > new < / button > < / div > </template> <script> export default { data () { return { msg: 'Vuex test! '}}, computed: {// Get state count() {return this.$store.state.count; }}, methods: {clickAdd() {this.$store. Dispatch ('add', 1); } } } </script> <style scoped> </style>Copy the code

Method of obtaining state objects

Used directly in the template of the component

<h2>{{ $store.state.count }}</h2>
Copy the code

Direct assignment in computed properties

// Method 1: Directly obtain computed: {count() {// this refers to a vue instance object in main.js return this.$store.state.count; }}Copy the code

Assign from the object of mapState

// Method 2: Use mapState computed: mapState({// es5 notation count: function (state) {return state.count; }, // count: state => state.count})Copy the code

Assign from an array of map states

// Method 3: Array get computed: mapState(['count'])Copy the code

Assign via JSON of mapState

// Method 4: JSON to obtain computed: mapState({count: 'count'})Copy the code

Mutations – getters – actions asynchronous

Mutations

$store.mit () : $store.mit (

// template <button @click="$store.mit ('ADD')">+</button (state) { state.count++; }}Copy the code

(2) Use mapMutations to introduce triggering

<template> <div class="hello"> <h1>{{ msg }}</h1> <h2>{{count}}</h2> <! - 3,,, directly call the corresponding method - > < button @ click = "ADD" > + < / button > < / div > < / template > < script > / / 1, to introduce mapMutations import {mapState, mapMutations} from 'vuex' export default { data () { return { msg: 'Vuex test! }, // For computed: mapState({count: 'count'}), add mapMutations methods to methods mapMutations([ 'ADD' ]) } </script> <style scoped> </style>Copy the code

Getters (get state and filter)

(1) Basic usage

// SRC /vuex/store.js const getters = {count: function(state){return state.count + 100; }}Copy the code

(2) Conventional acquisition value

Computed: {// Get getters count(){return this.$store.getters. Count; }}Copy the code

(3) mapGetters get the value

Open mutations import {mapState, mapMutations, mapGetters} from 'vuex'. Open mutations import {mapState, mapMutations, mapGetters} from 'vuex' mapGetters(["count"]) }Copy the code

Actions (Asynchronous state modification)

Actions and mutations function basically the same, but the difference is that Actions changes the state asynchronously, while mutations change the state synchronously. However, in practical projects, the value of mutations is generally changed through actions. (1) Add asynchronous code to store.js

// SRC /vuex/store.js const actions ={// trigger the corresponding method add ({commit}) {// add setTimeout(()=>{commit(' add ')) }, 3000); Console. log(' I execute ahead of reduce '); }}Copy the code

(2) Routine use

// template <button @click="add">+</button> // script methods: {add() {// Distribute action this.$store. }}Copy the code

(3) Use of mapActions

// template < button@click ="add">+</ button@click ="add"> MapActions} from 'vuex' mapActions(['add']) }Copy the code

Passing parameters

All you need to do is add the parameters in the corresponding locations of mutations and actions, and pass them in when you call them.

(1) SRC /vuex/store.js

Const mutations = {ADD (state, n) {state.count += n; Open open solutions add ({commit}, n) {setTimeout(()=>{commit(' add ', n); }, 3000); Console. log(' I execute ahead of reduce '); }}Copy the code

(2) Routine call transfer of page components

// template <button @click="add">+</button> // script methods: {add() {// Distribute action this.$store. }}Copy the code

(3) The page component invokes the pass using mapActions

// template <button @click="add(99)">+</button> // script methods: { ... mapActions(['add']) }Copy the code

The module – module group

When the application is very complex and has a lot of states, you need to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules, split in the same way from top to bottom.

General structure

// moduleA const moduleA = {state: {... }, mutations: { ... }, actions: { ... }, getters: { ... }} // moduleB const moduleB = {state: {... }, mutations: { ... }, actions: { ... }} // Const store = new vuex. store ({modules: {a: moduleA, b: moduleA, modules: ModuleB}}) // Value Store.state. a // -> moduleA status Store.state. b // -> moduleB statusCopy the code

In actual development, it is suggested to write modules separately. (1) the SRC/vuex/module1. Js

Open mutations = {state: {module1: {name: 'module1'}}, open mutations: { CHANGE1 (state, data) { state.module1 = data; }}, // Value getters: {module1: function(state){return state.module1; Actions: {change1 ({commit}, data) {commit (' change1 ', data)}}} export default module1;Copy the code

(2) the SRC/vuex/module2. Js

Open mutations = {state: {module2: {name: 'module2'}}, open mutations: { CHANGE2 (state, data) { state.module2 = data; }}, // Value getters: {module2: function(state){return state.module2; Actions: {change2 ({commit}, data) {commit (' change2 ', data)}}} export default module2;Copy the code

(3) the SRC/vuex/store. Js

// Import vue import vue from 'vue' // Import vuex import vuex from 'vuex' // Import module1 Import module1 from '@/vuex/module1' // Import module2 from '@/vuex/module2' // Import module2 from '@/vuex/module2' // Use vuex vue. use(vuex) // inject const store = new vuex.Store({modules: {a: module1, b: module2}}) // Export default store;Copy the code

(4) Component used, SRC/Compontent /one.vue

<template> <div id="app"> <! - module1 - > < h2 > {{module1. Name}} < / h2 > < button @ click = "change1 ({' name ':' change1})" > module1 change < / button > <! -- module2 --> <h2>{{ module2.name }}</h2> <button @click="change2({'name': 'change2'})">module2 </button> </div> </template> <script> MapActions} from 'vuex' export default {name: 'app', data () {return {}}, computed:{// mapState value //... MapState ({// module1: state => state.a.module1.name, // module2: state => state.b.module2.name //}) // The value of mapGetter... MapGetters (['module1', 'module2'])}, methods: {// mapAction... mapActions([ 'change1', 'change2' ]) } } </script> <style> </style>Copy the code

PS: Module name must be unique, otherwise there will be a conflict between fetching and changing values, currently test mapGetters can only fetch objects.

vue-router

Vue Router is the official route manager of vue.js. Its deep integration with vue.js core makes building single-page applications a breeze. The features included are:

  • Nested routing/view chart
  • Modular, component-based routing configuration
  • Route parameters, queries, and wildcards
  • View transition effect based on vue. js transition system
  • Fine-grained navigation control
  • Links with automatically activated CSS classes
  • HTML5 historical mode or Hash mode is automatically degraded in IE9
  • Custom scroll bar behavior

The installation

Install using command:

npm install vue-router --save
Copy the code

In the SRC /router/index.js file

Import vue from 'vue' import router from 'vue-router' import router from 'vue-router' import router from 'vue-router' Name it HelloWorld import HelloWorld from '@/components/HelloWorld' // Vue Globally use Router Vue. Use (Router) // Define route configuration export default New Router ({routes: [/ / configure routing, here is an array {/ / every link is an object path: '/', / / link path name: 'the HelloWorld, / / the name of the routing, component: HelloWorld // component template}]})Copy the code

Inject router into main.js with the following code:

// Import vue framework import vue from 'vue' // Import root component import App from './App' // Import router configuration import router from './router' // // Define instance new Vue({el: '#app', router, // inject framework components: { App }, template: '<App/>' })Copy the code

Page jump

Router-link indicates a router link

Router-link jumps within an HTML tag, corresponding to the hyperlink A tag, as follows:

<router-link to="/">Copy the code

To: Navigation path The following is an example:

<p> navigation: <router-link to="/"> </router-link> </router-link to="/hello"> Hello </router-link> </p>Copy the code

Programmatic navigation -JS code internal jump

In actual projects, most of the time it is through the JS code to navigate the jump, which is used as follows:

this.$router.push('/xxx')
Copy the code

(1) Write a button and bind the goHome() method to the button.

<button @click="goHome"> </button>Copy the code

(2) Add the goHome method to the

export default { name: 'app', methods: { goHome(){ this.$router.push('/home'); }}}Copy the code

Other Common methods

Back () this.$router.go(-1)Copy the code

Child routing – Routing nesting

Child routing, also called route nesting, is implemented by adding a route array to children, which is basically the same as other configured routes. You need to configure path and Component, and then add them in the corresponding part to display the child page information, which is equivalent to embedding iframe. Take a look at the following example:

SRC /components/ home.vue (parent page)

<template> <div class="hello"> <h1>{{ msg }}</h1> <! -- Add child routing navigation --> <p> Navigation: < the router - link to = "/ home" > home page < / router - the link > | < the router - link to = "/ home/one" > - child page 1 < / router - the link > | < the router - the link To ="/home/two">- </router-link> </p> <! --> <router-view/> </div> </template> <script> export default {name: 'Home', data () {return {MSG: 'Home Page! ' } } } </script> <style scoped> </style>Copy the code

SRC /components/ one.vue (subpage 1)

<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'One', data () { return { msg: 'Hi, I am One Page! ' } } } </script> <style scoped> </style>Copy the code

SRC /components/ 2.vue (subpage 2)

<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'Two', data () { return { msg: 'Hi, I am Two Page! ' } } } </script> <style scoped> </style>Copy the code

SRC /router/index.js (route configuration)

import Vue from 'vue' import Router from 'vue-router' import Home from '@/components/Home' import One from '@/components/One' import Two from '@/components/Two' Vue.use(Router) export default new Router({ routes: [ { path: '/', // Default page redirect: '/home'}, {path: '/home', // home route Name: 'home', Component: Home, children:[// nested child route {path:'one', // child page 1 Component: one}, {path:'two', // child page 2 Component: two},]}]})Copy the code

Routing parameters

through<router-link>The to parameter in the tag is passed

Basic syntax:

<router-link :to="{name:xxx, params: {key:value}}">valueString</router-link>
Copy the code

PS: “to” is preceded by a colon and followed by an object situation string

  • Name: Indicates the name value in the routing configuration file. It’s called named routing.
  • Params: The parameter to pass, which is in the form of an object in which multiple values can be passed.

SRC /components/ home.vue

<router-link :to="{name: 'one', params:{username:'test123'}}">Copy the code

SRC /router/indes.js add the following code to SRC /router/indes.js

{path:'one', // subpage 1 name: 'one', // Route name - Named route Component: one}Copy the code

SRC /components/ one.vue

<h2>{{$route.params.username}}</h2>
Copy the code

Pass parameters in the URL

SRC /router/index.js SRC /router/index.js SRC /router/index.js

{path:'/home/two/:id/:name', // subpage 2 Component: two},Copy the code

SRC/Components/two-.vuez

< p > ID: {{$route. Params. ID}} < / p > < p > name: {{$route. Params. Name}} < / p >Copy the code

SRC /components/ home.vue

<router-link to="/home/two/1/ 3 ">Copy the code

PS: To routes with colons before them are not string routes and must be matched. (4) If routing parameters need to have specific rules, they need to add regular expressions, as shown in the following example:

{path: '/ home/two / : id (\ d +) / : name', / / child pages 2 component: two}Copy the code

Programmatic navigation – Params passes parameters

(1) Add the following code to SRC /router/index.js:

{path:'/home/three', // subpage 3 name: 'three', Component: three}Copy the code

(2) Add the following code to SRC /components/ three. vue:

< p > ID: {{$route. Params. ID}} < / p > < p > name: {{$route. Params. Name}} < / p >Copy the code

SRC /components/ home.vue

Page 3 </button> </button> { toThreePage() { this.$router.push({name: 'three', params: {id: 1, name: 'zhangsan'}}) } }Copy the code

This.$router.push() does not use path with params, otherwise params will be invalid. You need to specify the page with name. B. The above parameters will not be displayed in the address bar of the browser. If you refresh the page once, you will not get the parameters.

{path:'/home/three/:id/:name', // subpage 3 name: 'three', Component: three}Copy the code

Programmatic navigation -query passes parameters

(1) Add the following code to SRC /router/index.js:

{path:'/home/three', // subpage 3 name: 'three', Component: three}Copy the code

(2) Add the following code to SRC /components/ three. vue:

< p > ID: {{$route. Query. ID}} < / p > < p > name: {{$route. The query. The name}} < / p >Copy the code

SRC /components/ home.vue

Page 3 </button> </button> { toThreePage() { this.$router.push({path: '/home/three', query: {id: 1, name: 'zhangsan'}}) } }Copy the code

/home/three? /home/three? id=1&name=zhangsan

Named Route – Named View – Redirection – Alias

After routing

Give a route a unique name and then jump to call that name. SRC /router/index.js add router name to SRC /router/index.js

{path: 'one', // subpage 1 name: 'one', // Route name - Named route Component: one // page component}Copy the code

SRC/Component/home.vue

Router-link :to="{name: 'one'}"> </router-link> router-push ({name: 'user'}})Copy the code

Named view

SRC /router/index.js SRC /router/index.js SRC /router/index.js

Import Vue from 'Vue' import Router from 'vue-router' const Header = {template: '<div>Header</div>' } const Left = { template: '<div>Left</div>' } const Right = { template: '<div>Right</div>'} vue. use(Router) export default Router({routes: [{path: '/', // Header, a: Left, b: Right } } ] })Copy the code

(2) in SRC/app. vue, code is as follows:

<template>
    <div id="app">
        <router-view />
        <router-view name="a" class="left" />
        <router-view name="b" class="right" />
    </div>
</template>

<script>
export default {
    name: 'App'
}
</script>

<style>
#app {
    text-align: center;
    color: #2c3e50;
    width: 500px;
    border: 1px solid red;
    margin: 0 auto;
}

.left,.right{
    float: left;
    width:48%;
    text-align: center;
    border:1px solid red
}
</style>
Copy the code

PS: As a matter of practice, named views can only be placed on top-level pages, i.e. the code in step 1 cannot be placed on other pages.

redirect

SRC /router/index.js SRC /router/index.js SRC /router/index.js SRC /router/index.js SRC /router/index.js SRC /router/index.js

Export default new Router({routes: [{path: '/', // redirect: '/home' // redirect}, {path: '/home', // home route Component: Home, children:[// nested subroute {path:'/ Home /two/:id/:name', // subpage 2 Component: two}, {path:'/ Home /three/:id/:name', / / child pages 3 name: 'three', / / the name of the routing - named routing redirect: '/ home/two / : id/name'} / / redirection - transfer parameters,]]}})Copy the code

SRC /components/ home.vue

< the router - link to = "/" > home page < / router - the link > | < the router - link to = "/ home/two / 1 / lisi" > child page 2 < / router - the link > | < the router - link: to = "{name: 'three', params: {id: 1, name: 'zhangsan'}}">Copy the code

Note 1- Redirection without parameters:

Redirect: '/home' // redirect - with no parametersCopy the code

2- Redirection with parameters:

Redirect: '/home/two/:id/:name' // Redirect - Pass parametersCopy the code

The alias

SRC /router/index.js SRC /router/index.js SRC /router/index.js SRC /router/index.js SRC /router/index.js SRC /router/index.js

{path:'/one', // sub page 1 Component: one, alias: '/oneother'}Copy the code

SRC /components/ home.vue

<router-link to="/oneother"> subpage 1</router-link>Copy the code

Explanation 1: The difference between redirect and alias

  • Redirect: Changes the URL value directly, making the URL the real path. \
  • Alias: THE URL path does not change, this is more friendly, let the user know their access path, just changed<router-view>The content of.

Note 2: Do not use aliases in path ‘/’. Aliases in the following codes do not work.

{
    path: '/',
    component: Hello,
    alias:'/home'
}
Copy the code

Transition animations

Code sample

(1) Add a
tag to the

tag. The tag also needs a name attribute.

<transition name="fade" mode="out-in">
    <router-view />
</transition>
Copy the code

(2) Add CSS, there are four CSS class names, and four class names are related to the transition name attribute, such as name= “fade”. The corresponding CSS is as follows:

/* Page switch animation */ /* Enter the end state of transition, which takes effect when the element is inserted, and is removed after the transition process is complete */. } /* Enter the beginning state of the transition, which takes effect when the element is inserted, and is deleted immediately after only one frame is applied */. } /* After leaving the beginning of the transition, the element is triggered when it is deleted, and deleted immediately after applying only one frame */. Fade-leave {opacity: 1; } /* The end state of the transition, which takes effect when the element is deleted, and will be deleted after the transition is completed */. transition: opacity .5s; }Copy the code

Transition mode

  • In-out: The new element enters the transition first, and the current element leaves after it completes. Default mode.
  • Out-in: The current element transitions out first, and the new element transitions in after leaving.

Mode with 404

Mode pattern

Code examples:

Export default new Router({mode: 'history', //mode mode routes: [...] })Copy the code

Value mode: (1) the histroy: URL like normal URL, example: http://localhost:8080/home (2) the hash: default values, will be more than a “#”, example: http://localhost:8080/#/home

404 Page Settings

/ SRC /router/index.js add the following code to the/SRC /router/index.js directory:

// 404
{
    path: '*',
    component: () => import('@/components/404')
}
Copy the code

SRC /components/404.vue

<template>
    <div class="hello">
        <h1>404 not found</h1>
    </div>
</template>
<script>
export default {
    data () {
        return {

        }
    }
}
</script>

<style scoped>
</style>
Copy the code

Routing hooks

Vue-routers have three types of routing hooks:

  1. Global hooks: most commonly used
  2. Route separate hook
  3. Component internal hook

Global hooks

SRC /router/index.js

Const router = new VueRouter({... }) // Global route interception - execute router.beforeeach ((to, from, next) => {// Add global login judgment here // continue next(); }); Router.aftereach (() => {// does not accept next}); export default router;Copy the code

Each hook method takes three arguments: to: Route: the destination to enter [Route object] from: Route: the current navigation Route to leave next: Function: continue the Function

  • Next () : Continue execution
  • Next (false) : interrupts current navigation.
  • Next (‘/’) or next({path: ‘/’}) : jump to a new page, often used to jump to a failed login

Route separate hook

SRC /router/index.js add hooks to route configuration as follows:

{path:'/home/one', // subpage 1 Component: one, // Routing inner hook beforeEnter: (to, from, next) => {console.log(' execute before entering '); next(); }}Copy the code

Component internal hook

Use: to define hook functions within a routing component:

  • BeforeRouteEnter: called before entering the page
  • BeforeRouteUpdate (added in 2.2) : This parameter is invoked when the page route changes
  • BeforeRouteLeave: Leave the page call

Find an arbitrary page and write the following code:

<script> export default { name: 'Two', data () { return { msg: 'Hi, I am Two Page! '}}, // call beforeRouteEnter(to, from, next) {console.log(' Enter router hook ') next()}, BeforeRouteLeave (to,from, next){console.log(' enter leave route hook ') next()}, beforeRouteUpdate(to, From, next) {console.log(' enter update route hook ') console.log(to.params.id) next()}} </script>Copy the code

Route lazy loading

Normal routing mode:

{path: '/ Home', component: Home}Copy the code

Lazy loading mode

In large projects, in order to improve the efficiency of page initialization, routing is generally used in lazy load mode, a total of three implementations. (1) The first way to write:

component: (resolve) => require(['@/components/One'], resolve)
Copy the code

(2) The second way to write:

component: () => import('@/components/Two')
Copy the code

(3) The third way to write:

components: r => require.ensure([], () => r(require('@/components/Three')), 'group-home')
Copy the code

PS:

  • The second abbreviation is commonly used
  • In the third way, ‘group-home’ is to pack components into blocks. Multiple components can be put into this group. During the packaging, Webpack will pack all asynchronous modules under the same chunk into one asynchronous block.

vue-cli

Vue-cli is a scaffold for fast building single page applications, which integrates WebPack, NPM, NodeJS, Babel, Vue, Vue-Router, etc.

Global Installation vUE – CLI, command line:

npm install vue-cli -g
Copy the code

Initialize the project

In actual development, the webpack template is usually used, and the command is as follows:

vue init webpack my-vue-demo
Copy the code

Run the project

npm run dev
Copy the code

The above commands run the project in development mode

npm run build
Copy the code

The above commands package the project release

Main.js (entry file)

// Import vue framework import vue from 'vue' // Import root component import App from './App' // Import router configuration import router from './router' // ProductionTip = false // Define instance new Vue({el: '#app', router, Components: {app}, template: '<App/>' })Copy the code

Router configuration

Import vue from 'vue' import router from 'vue-router' import router from 'vue-router' import router from 'vue-router' Name it HelloWorld import HelloWorld from '@/components/HelloWorld' // Use route dependency vue. use(Router) // Define route configuration export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld } ] })Copy the code

The template

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title>Vue component </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <! <h2 style="color:red"> </h2> </template> </div> <! -- script tag template --> <script type="x-template" id="demo3"> <h2 style="color:red" Type ="text/javascript"> // instantiate new Vue({el: '#app', data: {message: 'hello'}, / / / / options template template: ` < h1 style = "color: red" > I am option template < / h1 > ` / / template: '# demo2 template:' # demo3}); </script> </body> </html>Copy the code

The component registration

(1) Global registration

// script Vue.component('button-counter', { data: function () { return { count: 0 } }, template: '< button v - on: click = "count++" > global components display: {{count}} < / button > "}); new Vue({ el: '#app' }); <button-counter></button-counter>Copy the code

(2) Local registration

// script new Vue({ el: '#app', components:{ "button-inner":{ data: function() { return { inner: 0 } }, template: '< button v - on: click = "inner++" > partial components display: {{inner}} < / button >'}}}); </button-inner> </button-inner>Copy the code

Custom instruction

Custom directives in vue are implemented through vue. directive

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title>Vue start custom directive </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <div v-test="color"> {{num}} </div> <button onclick="unbindApp()"> </button> <script type="text/javascript"> app.$destroy(); } // Vue. Directive ("test",{//1- bind bind:function (el, binding, vnode) {console.log("1-bind "); console.log("el:",el); console.log("binding:",binding); console.log("vnode:",vnode); el.style.color = binding.value; }, //2- inserted:function (el, binding, vnode) {console.log("2-inserted "); }, //3- update:function (el, binding, vnode) {console.log("3-update "); }, / / 4 - update complete componentUpdated: function (el, binding, vnode) {the console. The log (" 4 - componentUpdated update complete "); }, //5- unbind:function (el, binding, vnode) {console.log("5-unbind "); }}); var app = new Vue({ el:'#app', data:{ num: 123, color:'red' } }) </script> </body> </html>Copy the code

Parameters that

  • El: The element bound by the directive that can be used to manipulate the DOM directly
  • Binding: An object that contains a lot of information about the directive
  • Vnode: : Virtual node generated by Vue compilation

$on (adds events outside the constructor)

$on takes two arguments, the first being the name of the event when it is called and the second an anonymous method

$on('reduce',function(){console.log(' reduce()'); this.count--; });Copy the code

$once (event executed once)

App. $once('reduceOnce',function(){console.log(' method executed only once '); this.count--; });Copy the code

$off (Close event)

Function off(){console.log(' close event '); app.$off('reduce'); }Copy the code

extends

Extend: Extend the constructor

Var extendObj ={created: function(){console.log(" I am extended "); }} var app = new vue ({// mount instance el:'#app', // page data initialization, characters, objects, array data:{}, // extends: extendObj})Copy the code

📚 Nuggets article

  • Daily Front-end summary
  • A rare primer on TypeScript systems
  • JS Sunflower treasure Book secret notes, escort for you gold three silver four
  • TypeScript learns early to become competitive in the workplace
  • More than 234.77 million words in front-end simulation interview
  • JavaScript data structure of the chain table | technical review
  • JavaScript data structures – Collections | Technical Review
  • This was my first JavaScript primer
  • A qualified junior front-end engineer needs to master module notes
  • [Primary] Personally share notes of Vue front-end development tutorial
  • LocalStorage and sessionStorage localStorage
  • Drag and drop in HTML5
  • Challenge the front-end HTTP/ECMAScript
  • 170 Interview questions + answer Learn to organize (conscience making)

❤️ follow + like + Favorite + comment + forward ❤️

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time. This article has been included in www.1024bibi.com

Star: github.com/webVueBlog/…