preface

Recently, I am sorting out some content of Vue, including Vue 3.0 new features,Vue 2.0 features and implementation methods, as well as Vue bucket content, involving more content, so I find an opportunity to send an article, all the points out. It looks good. All right, let’s get started.

The body of the

1 Comparison between Vue 3.0 and Vue 2.0

1.1 New features and principles of Vue 3.0

1.1.1 Observation mechanism

Description: More sophisticated, precise, and efficient for debugging responsive tracing. Added an API for creating Observables.

In version 3.0 there will be a proxy-based observer that will provide responsive tracing with full language coverage. The new implementation is more powerful than the observer based on Object.defineProperty in the 2.x version:

  • You can detect the addition and deletion of attributes
  • Can detect array index changes and length changes
  • Supports Map, Set, WeakMap, and WeakSet
  • The Proxy mentioned above is one of the biggest highlights of Vue 3.0. It not only replaces the Object. DefineProperty method of Vue 2.0 and is 100% faster in assembly generation, but also doubles/reduces the normal memory usage

    Here is a simple Proxy implementation:

    let obj = {
        	a : 1
    }
    let proxyObj = new Proxy(obj,{
        get : function (target,prop) {
            return prop in target ? target[prop] : 0
        },
        set : function (target,prop,value) {
            target[prop] = 888;
        }
    })
        
    console.log(proxyObj.a);        // 1
    console.log(proxyObj.b);        // 0
    
    proxyObj.a = 666;
    console.log(proxyObj.a)         // 888
    Copy the code

    In the example above, we define an object obj, generate a proxyObj object through the Proxy constructor, and modify its set(write) and get (read) behavior.

    If we attempt to access a non-existent attribute, 0 will be returned. That is, when we access proxyObj. A, the original object has a attribute, so 1 will be returned. When we attempt to access b, the non-existent attribute, Instead of returning undefined, we return 0. When we try to set a new property value, we always return 888. Therefore, even if we assign proxyobj. a 666, it doesn’t work, it still returns 888!

    To learn more about Proxy, check out Ruan Yifeng’s great introduction to ECMAScript 6 here: es6.ruanyifeng.com/#docs/proxy

    The new observer also has the following characteristics:

  • Provides an API for creating observables. For small to medium sized applications, the API provides a lightweight, simple solution for managing state across components.
  • An Immutable observable. We can create multiple immutable versions of a value in case someone modifies its properties, which must be temporarily unlocked internally. This mechanism can be used to freeze properties passed to child components or state changes outside the Vuex state tree.
  • More powerful debugging capabilities. We use new renderTracked and renderTriggered hooks to find out exactly when and by whom a component’s render is triggered.
  • It’s easy to know why a component is rerendered

    1.1.2 Other runtime enhancements

    Smaller, faster, tree-shaking, fragment, portal, custom render

    It’s smaller. The new code base was designed with tree-shaking in mind. Built-in components (such as) and built-in directives (V-Models) are brought in on demand, supporting tree-shaking. The new runtime minimum size will be less than 10KB (after GZIP). In addition, since many of the features are tree-shaking supported, we can provide more built-in features so that if you don’t want to use them, your code size won’t increase at all. For the record,Vue 2.0 is twice as big as Vue 3.0

    Faster, including virtual DOM mounting and updating, component instance initialization, and observer creation. Version 3.0 will cut your app startup time in half.

    Supports fragment and Portal. Although smaller in size, version 3.0 brings new features, including support for Fragments (a component containing multiple root nodes) and Portal (rendering a subtree in the DOM instead of in a component).

    Slot mechanism enhanced. All compile-generated slots are now functions that are called on the render call of the child component. In this way, the dependencies in the slot are considered child dependencies rather than parent dependencies. This means: 1. When the slot contents change, only the child components are re-rendered; When the parent component is re-rendered, if the slot content has not changed, the child component does not need to be re-rendered. This feature provides more accurate change detection at the component tree level, so there is less useless rendering.

    Customize render. We will provide an API to create custom render, so you don’t need to fork Vue code to customize some functionality. This feature makes it easier for projects like Weex and NativeScript Vue.

    >1.1.3 Compiler enhancements

    Summary: Compiled content is tree-shaking friendly, more AOT optimizations, better error notification, better source map support.

    In order to output tree-shaking friendly code, if some optional features are used in the template, the generated code will import those features using ES module syntax. Therefore, optional features that are not used will not appear in the final code.

    As a result of the optimization of the virtual DOM, there are more efficient compile-time optimizations such as static tree enhancement, static attribute enhancement, adding compilation hints to the runtime to reduce child normalization, and fast paths created by VNode.

    Rewrite the parser to add location information to template compilation error prompts. This will also enable Vue to support source maps for templates. The new parser can be made available to third-party tools, such as ESlint-plugin-vue and IDES.

    1.2 Comparison between Vue 3.0 and Vue 2.0

    1. Lazy observation is performed by default. In 2.x, however, observers are created for data of any size at the beginning. When the data is large, this can cause significant performance pressure when the page loads. The 3.x version will only create observers for “data that was used to render the initial visible portion”, and 3.x observers are more efficient.

    2. More accurate change notification. In version 2. X, when you use vue. set to add a property to an object, all the watcher of that object is rerun. In version 3. X, only watcher that depends on that property will run again.

    For the time being, there are no major API changes between Vue 3.0 and Vue 2.0, but relative to the principles of Vue 3.0 Refactoring with TypeScript is a major improvement in all aspects of performance (compared to 2.0), and work has been going on since version 2.6. Although the improvement is not obvious, I believe that Vue3.0 will give us a bigger surprise.

    2. Vue 2.0

    2.1 Differences between MVVM framework and ordinary framework and the way Vue2.0 is implemented

    2.1.1 MVVM framework

    MVVM framework (Jquery):

    MVVM is model + View + ViewModel framework, through the ViewModel to connect the data model model and view

    A Vue is data-driven. The Vue itself binds the DOM to the data. Once the binding is created, the DOM and the data stay in sync and the DOM changes as the data changes.

    The ViewModel is the heart of Vue and is an instance of Vue. The Vue instance is scoped to an HTML element, which can be body or the element referred to by an ID.

    DOM Listeners and Data Bindings are the key to realize bidirectional Bindings. DOM Listeners monitor the changes of all View layer DOM elements on the page. When changes occur, data in the Model layer changes accordingly. Data Bindings listens to Model layer Data. When Data changes, DOM elements in View layer change accordingly.

    2.1.2 Differences between MVVM framework and common framework

    Difference: VUE is data-driven and uses data to display view layers rather than node operations

    2.1.3 Vue2.0 implementation and bidirectional binding JS implementation examples

    Now that we know the difference, let’s take a look at the principle of VUE bidirectional binding, which can be summarized in one sentence:

    Vue. js adopts data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty() to publish messages to subscribers when data changes and trigger corresponding listening callback.

    Js to achieve a simple two-way binding

    <body>
        <div id="app">
        <input type="text" id="txt">
        <p id="show"></p>
    </div>
    </body>
    <script type="text/javascript">
        var obj = {}
        Object.defineProperty(obj, 'txt', {
            get: function () {
                return obj
            },
            set: function (newValue) {
                document.getElementById('txt').value = newValue
                document.getElementById('show').innerHTML = newValue
            }
        })
        document.addEventListener('keyup'.function (e) {
            obj.txt = e.target.value
        })
    </script>
    Copy the code

    2.2 Vue life cycle and application scenarios

    2.2.1 Vue life cycle

    Now that we’ve talked about the principle, we have to talk about Vue’s characteristic lifecycle:

    First, there are 8 stages: before/after creation, before/after loading, before/after update, before/after destruction.

    Before/After creation:

    BeforeCreate (before creation) before data observation and initialization events have started

    Created completes data observation, property and method operations, initialization events, and the $EL property is not yet displayed

    Before/after loading

    BeforeMount is called before the mount begins and the associated render function is called for the first time. The example completes the following configuration: compile the template, and generate HTML from the data inside the data and template. Note that the HTML is not mounted to the page at this point.

    Mounted after el is replaced by a newly created vm.$el and mounted to the instance. The example is configured to replace the DOM object pointed to by the EL attribute with the HTML compiled above. Finish rendering the HTML from the template to the HTML page. Ajax interactions occur during this process.

    Before/after update

    BeforeUpdate is called before data is updated and occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional rerendering.

    Updated is called after the virtual DOM is re-rendered and patched due to data changes. When called, the component DOM is already updated, so DOM-dependent operations can be performed. In most cases, however, you should avoid changing the state during this period, as this can lead to an infinite update loop. This hook is not called during server-side rendering.

    Before/after destruction

    BeforeDestroy called before instance destruction. The instance is still fully available.

    Called after the instance is destroyed. When called, all event listeners are removed and all subinstances are destroyed. This hook is not called during server-side rendering.

    To summarize what is the vUE lifecycle:

    The lifecycle of a Vue instance is the process from creation to destruction. The life cycle of a Vue is a series of processes from the beginning of creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and destroying. BeforeCreate, created, created, beforeMount, mounted is triggered when the first page is loaded, and DOM rendering is done in Mounted

    2.2.1 The Vue life cycle is suitable for those scenarios

    Mounted can be used for either of the loading events or for both of the loading events. Mounted can be used for either of the loading events or for both of the loading events. Updated: If data is handled uniformly, write the corresponding function here. BeforeDestroy: You can make an acknowledgement box for the stop event nextTick: Domarguments is a pseudo-array that has no traversal interface and cannot be traversed.

    2.3 the Vue instruction

    Vue is divided into internally specified instructions and custom instructions.

    2.3.1 Vue internal instructions

    Vue internal instructions include v-for, V-if, V-bind, V-ON, V-show, and V-else. These are not comprehensive but most commonly used.

    Modifiers are then included: prevent: Submit events that no longer reload the page; . Stop: prevents the click event from bubbling. .self: Fires when an event occurs in the element itself rather than a child element; .capture: event listening, which is called when an event occurs and is often used in projects.

    In addition, v-ON can bind multiple events as well as the V-show command. The difference between V-IF and V-ON is that:

    Conditional render directives, which, unlike V-if, allow elements to exist in HTML code regardless of whether v-show is true or false; The element will only exist in HTML code if v-if is true. The V-show directive simply sets the style value of the element’s CSS

    V-bind is used as a two-way bind, and v-for is used as a loop to load a list. V-for has a key value, which can be used as a key:

    When vue.js is updating a rendered element list with V-for, it defaults to a “reuse in place” strategy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element here and make sure it shows every element that has been rendered under a specific index. The key’s main purpose is to update the virtual DOM efficiently.

    Modifiers are not much to explain, you can go to the official website to explain:

    The vue web site:

    Vue Chinese official website

    Cn.vuejs.org/v2/guide/in…

    2.3.2 Vue Custom Commands

    Global directives: The directive method of a Vue object takes two arguments, the directive name and the function. Inserted (when the node is inserted), UPDATE (related updates within the component) hook function parameters: EL, binding

    2.4 Vue calculation properties and Watch monitoring

    Putting too much logic into a template can make the template too heavy and difficult to maintain, so try to compute attributes in cases where complex processing of data is required and may be used multiple times. Benefits: (1) the data processing structure is clear; (2) Rely on data, data update, processing results automatically update; ③ Inside the attribute this points to the VM instance; (4) When template is called, write the calculation attribute name directly. ⑤ Commonly used is getter method, get data, can also use the set method to change the data; (6) Compared with methods, methods recalculates regardless of the dependent data. However, when the dependent data does not change, computed data is obtained from the cache and does not recalculate. Here is an example of the basis for calculating attributes:

    <div id="app">
        <input v-model = "lastName" >
        <input v-model = "firstName" >
        {{ quanming }}
    </div>
    
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                firstName: 'health',
                lastName: 'wu'
            },
            computed: {
                quanming:{
                    get:function() {return this.lastName + this.firstName
                    }
                }
            }
        });
    </script>
    Copy the code

    Watch in VUE is an important concept, through which we can detect changes in data. Here is a simple example:

    <div id="app">
        <input v-model = "lastName" >
        <input v-model = "firstName" >
        {{ fullName }}
    </div>
    
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                firstName: 'health',
                lastName: 'wu',
                fullName: 'jasonwoo'
            },
            watch: {
                firstName: function (val) {
                    this.fullName = this.lastName + val
                },
                lastName: function (val) {
                    this.fullName = val + this.firstName
                }
            }
        });
    </script>
    Copy the code

    In addition, the watch property is commonly used, so I’ll elaborate on its advanced use — to listen for property changes on objects:

    1. The monitoring object needs deep monitoring. The following code can monitor the changes of the entire MSG object

    watch: { &emsp; &emsp; msg: { &emsp; &emsp; &emsp; &emsp; handler(newValue, oldValue) { &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; console.log(newValue) &emsp; &emsp; &emsp; &emsp; }, &emsp; &emsp; &emsp; &emsp; deep:true&emsp; &emsp; }}Copy the code

    2. Monitor changes in an attribute in an object using computed middle-layer computing

    computed: {
    &emsp;channel() { &emsp; &emsp; &emsp;returnthis.msg.channel &emsp; } }, watch:{ channel(newValue, oldValue) { &emsp; &emsp; &emsp; &emsp; console.log('new: %s, old: %s', newval, oldVal) &emsp; &emsp; &emsp; &emsp; // This allows you to do whatever you want if the value of the listener changes &emsp; &emsp; }}Copy the code

    2.5 the Vue components

    Two of the most important concepts in VUE are data-driven, which we’ve talked about above, and component mechanism, which we’ll talk about in more detail

    2.5.1 Vue introduces components

    1. Use ES6 import… from … The syntax or CommonJS require() method introduces components

    Vue.component(‘my-component’, {template: ‘Vue.component(‘my-component’, {template:’)

    A custom component!


    3. Use components

    Here’s a quick example:

    Vue.component('componentName'{/ * * / component}); Vue.component(Vue.component)'mine',{           
        template:'#mineTpl',          
        props:['name'.'title'.'city'.'content']}); var v=new Vue({ el:'#vueInstance',      
        data:{          
            name:'zhang',          
            title:'this is title',         
            city:'Beijing',         
            content:'these are some desc about Blog'}});Copy the code

    2.5.2 How do I Make the CSS Work only in the current Component

    Modify the current component < style > to < style scoped >

    2.5.3 What is the keep-alive function of the component

    < keep-alive >< /keep-alive > Caches inactive component instances when wrapping dynamic components, mainly to preserve component state or avoid re-rendering.

    In plain English: for example, if there is a list and a detail, then the user will often execute open details => return to the list => Open details… In this case, both the list and the details are a very frequent page, so you can cache the use of the list component.

    This way, each time the user returns the list, it can be quickly rendered from the cache instead of re-rendered

    2.5.4 Vue Component Encapsulation Process (Text Description)

    First, components can improve the development efficiency of the entire project. Abstract the page into several relatively independent modules, solve our traditional project development: low efficiency, difficult to maintain, reuse and other problems.

    Then, create a component using the vue.extend method and register the component using the Vue.component method. Subcomponents need data, which can be defined in props. After modifying the data, the child component wants to pass the data to the parent component. You can use the emit method.

    2.6 Communication between Components

    2.6.1 Communication between Parent and Child Components

    Parent and child components pass values: Props

    Child component passes data to parent component: Child component passes parameters through $emit method, triggering parent component event

    2.6.2 Bus communication

    Check out my previous post on Bus communication:

    Repeated triggering solutions and bugs in Vue EventBus usage

    In addition, vuEX communication is explained below

    2.7 Differences between Vue, Angular, and React

    Components are a general overview, but how does Vue differ from the other two frameworks Angular and React?

    2.7.1 VUE is different from Angular and Angular dirty check is understood

    2.7.1.1 The difference between VUE and Angular

    Similarities:

    Both support directives: built-in directives and custom directives. Both support filters: built-in filters and custom filters. Both support bidirectional data binding. None of them support low-end browsers.

    Difference:

    1.AngularJS is expensive to learn, such as adding Dependency Injection, while vue.js provides simple and intuitive apis. 2. In terms of performance, AngularJS relies on dirty checking of data, so the more Watcher, the slower it is. Vue.js uses dependency tracing based observations and uses asynchronous queue updates. All the data is triggered independently. For large applications, this optimization difference is quite obvious.

    2.7.1.2 Angular Dirty Check Understanding

    Angular has no way to tell if your data has changed, so it sets some criteria. When you trigger these criteria, it performs a check to walk through all the data, compare where you changed, and perform the change. This test is very unscientific. And it’s not very efficient, there are a lot of redundant places, so it’s officially called dirty inspection.

    2.7.2 Difference between a Vue and a React and function of write Keys in React/Vue components

    2.7.2.1 Difference between Vue and React

    Similarities:

    React uses a special JSX syntax, and Vue. Js is also used in component development. Vue has a special file format, and has conventions for file contents. The central idea is the same: Everything is a component, and component instances can be nested. Both provide reasonable hook functions that developers can customize to handle requirements. None of them have column count AJAX, Route, etc. built into the core package, but are loaded as plug-ins. The feature of mixins is supported in component development.

    Difference:

    React relies on the Virtual DOM, whereas vue.js uses the DOM template. React uses the Virtual DOM to do dirty checks on rendered results. Vue.js provides instructions, filters, etc. in templates that make it easy to manipulate the DOM quickly.

    2.7.2.2 React/Vue Function of Write Keys in Components

    During development, we need to ensure that an element’s key is unique among its siblings. In the Diff algorithm, the Key value of an element is used to determine whether the element is newly created or moved, so as to reduce unnecessary element re-rendering.

    2.8 Vue routing implementation: Hash mode and history mode

    2.8.1 hash pattern

    In the browser, the symbol “#”, # and the characters after # are called hashes, which are read with window.location.hash; Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages. In hash mode, only the content before the hash symbol is included in the request, such as http://www.xxx.com. Therefore, the back end will not return a 404 error even if the route is not fully covered.

    2.8.2 history pattern

    History uses new HTML5 features; Two new methods are provided: pushState (), replaceState () to modify the browser history stack, and popState events to listen for state changes. The history mode, the front end of the URL must be initiated and the actual backend requested URL, such as http://www.xxx.com/items/id. The back end will return a 404 error if there is no routing for /items/ ID. Vue-router’s official website states: “However, this mode needs to be configured in the background to play well… So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app depends on.”

    2.9 Hook functions of Vue routes

    The home page can control navigation jump, beforeEach, afterEach, etc., generally used for page title modification. Some require login to adjust the page’s redirection function. BeforeEach has 3 arguments to, from, next: to: route The destination route object to enter, from: route The current navigation route to leave next: function Must call this method resolve the hook. The execution depends on the call parameters of the next method. You can control the jump of web pages.

    2.10 Single-page applications such as Vue and their advantages and disadvantages

    Advantages: The goal of Vue is to implement data binding and composite view components for responses through as simple an API as possible, with a data binding system for responses at its core. MVVM, data-driven, componentized, lightweight, simple, efficient, fast, module-friendly.

    Disadvantages: Does not support earlier versions of browsers, as low as IE9; Not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); The first time to load the home page is relatively long; You can’t use the browser’s navigation buttons. You need to move forward and backward.

    Vue family barrel

    3.1 VuE-CLI Usage and working principles

    3.1.1 VUE-CLI

    First go to the project directory on the command line and type:

    vue init webpack Vue-Project
    Copy the code

    Where webpack is the template name, you can see more templates at vue.js GitHub github.com/vuejs-templ…

    Vue-project is a user-defined Project name. After the command is executed, a Project folder named with this name will be generated in the current directory

    After the configuration is complete, you can see that there is an extra Project folder in the directory, which is a vue.js Project based on Webpack created by vue-CLI. Then go to the Project directory (CD vue-project) and use CNPM to install dependencies

    cnpm install
    Copy the code

    And then start the project

    npm run dev
    Copy the code

    Package online

    npm run build
    Copy the code

    3.1.2 VUE-CLI Principle

    Here is not a detailed introduction of vuE-CLI principle, post an article this article about the principle of the more detailed, VUe-CLI principle in the following article I will carry out with you in detail, the following is the address of the article

    Vue-cli principle analysis

    3.2 Use of Vue Axios

    3.2.1 What is AXIos and how is it used

    A module that requests background resources. NPM install axios -s install axios -s install axios -s install axios -s install axios -s If the background is Tp5, define a resource route. Js with import coming in and then.get or.post. Returns success in the.then function and failure in the.catch function

    1. GET request

    // create request axios.get() for user with given ID'/user? ID=12345')
      .then(response=>{
        console.log(response);
      })
      .catch(function(error) { console.log(error); }); // implement axios.get('/user'}). Then (response=>{console.log(response); }) .catch(function (error) {
        console.log(error);
      });
    Copy the code

    2. A POST request

    axios.post('/user'{// post is an object to pass firstName:'Fred',
        lastName: 'Flintstone'
      })
      .then(response=>{
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    Copy the code

    3. Execute multiple concurrent requests

    function getUserAccount() {
      return axios.get('/user/12345');
    }
    function getUserPermissions() {
      return axios.get('/user/12345/permissions');
    }
    axios.all([getUserAccount(), getUserPermissions()])
      .then(axios.spread(function(acct, perms) {// Two arguments representing the result returned // This function will be triggered when both requests are completed});Copy the code

    Request method – Alias list

            axios.request(config)

            axios.get(url[, config])

            axios.delete(url[, config])

            axios.head(url[, config])

            axios.post(url[, data[, config]])

            axios.put(url[, data[, config]])

            axios.patch(url[, data[, config]])

    concurrent

    Axios. all(iterable)// Iterable is an iterable of arguments such as groups of numbers, etc

    Axios.spread (callback)// Callback is not executed until all requests have been completed

    3.2.2 Used in conjunction with VUE-AXIOS

    First referenced in the main entry file main.js:

    import axios from 'axios'
    import VueAxios from 'vue-axios'
    
    Vue.use(VueAxios,axios);
    Copy the code

    Then you can use methods in the component file:

    getNewsList(){
          this.axios.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); })}Copy the code

    I’ll write a whole article about Axios later.

    3.3 Vuex state management attributes and characteristics and actual combat

    3.3.1 Vuex Status Management Attributes

    Vuex has five properties: State, Getter, Mutation, Action and Module

    3.3.1.1 state

    State is a single state tree, in which we need to define the array, object, string, etc., we can get the state of the object you define in vue.js components only if it is defined here.

    3.3.1.2 getter

    When we need to derive some state from the store state, we need to use the getter. The getter receives state as the first argument, and the return value of the getter is cached based on its dependencies. It is recalculated only when the dependent value in the getter (something in state that requires derived state) changes.

    3.3.1.3 mutation

    The only way to change the state in a store is to submit mutation, which is a similar event. Each mutation has a string event type and a callback function where we need to change the value of state. To execute this callback, we need to execute a corresponding calling method: store.mit.

    3.3.1.4 action

    An action can commit mutation, store.mit can be executed within the action, and any asynchronous operation can be performed within the action. If we want to use this action on the page, we need to execute store.dispatch

    3.3.1.5 module

    The Module simply solves the problem when state is very complex and bloated. The Module can split the store into modules, each with its own state, mutation, action, and getter.

    3.3.2 Vuex Status Management Features

    3.3.2.1 VuEX State Feature

    Vuex is a warehouse with many objects in it. The Vue component reads the data from the Store. If the data in the Store changes, the Vue component reads the data from the store. Components that depend on this data are also updated. 3. It maps global state and getters to computed properties of the current component using mapState

    3.3.2.2 Vuex Getter Feature

    Getters can be used to calculate State, which is the calculated property of Store. 2. Although it can also be used to calculate property within components, getters can be reused between multiple components

    3.3.2.3 Mutation characteristics of VUEX

    (2) The Action is similar to mutation, except that it does not commit any mutation directly. Actions can contain any asynchronous Action

    3.3.3 Vuex cognition

    Vuex can be understood as a development pattern or framework. PHP has ThinkPHP, Java has Spring, etc. Changes to driver components are centrally managed through state (data sources) (just as Spring’s IOC container centrally manages beans). Application-level state is centralized in the Store; The way to change that is to submit mutations, which is a simultaneous thing; Asynchronous logic should be encapsulated in actions.

    3.3.3 Vuex actual combat

    Actual combat content I have written before the article introduced, here posted an address to welcome you to see:

    Learn how to use the Vuex method

    3.3 VuE-Router application method and actual combat

    3.3.1 Vue-Router navigation hooks and their parameters.

    Navigation hooks are:

    A/Global hooks and exclusive hooks within components. B /beforeRouteEnter, afterEnter, beforeRouterUpdate, beforeRouteLeave

    Parameters:

    There are to (the route to), from (the route to leave), and next (be sure to use this function to get to the next route, or intercept it if you don’t use it)

    3.3.2 Vue-router Defines dynamic routes and obtains transmitted dynamic parameters

    Add /:id to the path attribute in the index.js file in the Router directory.

    Use the params.id of the Router object.

    3.3.3 Definition of vue-Router Nested routines

    In real projects we will encounter a combination of multi-layer nested components, but how do we implement nested components? Therefore, we need to use the children configuration in the parameters of the VueRouter, so that we can achieve good route nesting. Index.html, with only one exit

    <div id="app"> <! <router-view></router-view> </div>Copy the code

    Main.js is a redirect that displays the home component as soon as the page loads. The redirect must be consistent with the path component. Children is the child route, and of course the child route can also be nested in the child route.

    import Vue from 'vue'  
    import VueRouter from 'vue-router'Vue.use(VueRouter) // Import two components import home from"./home.vue"  
    import game from "./game.vue"// const routes = [{path:"/", redirect: "/home"},// redirect to the home component {path:"/home", component: home,  
            children: [  
                { path: "/home/game"Const router = new VueRouter({routes}) new Vue({el:'#app',  
        data: {  
        },  
        methods: {  
        },  
        router  
    })
    Copy the code

    Home.vue, click “Show” to display the child route. The exit of the child route must be inside the parent route, otherwise the child route cannot be displayed.

    <template> <div> <h3> home </h3> <router-link to="/home/game">< button> display <tton> </router-link> <router-view></router-view> </div> </template>Copy the code

            game.vue

    <template> <h3> Game </h3> </template>Copy the code

    3.3.3 Vue-Router navigation hooks

    Global navigation hook

            router.beforeEach(to, from, next),

            router.beforeResolve(to, from, next),

            router.afterEach(to, from ,next)

    Component internal hook

            beforeRouteEnter,

            beforeRouteUpdate,

            beforeRouteLeave

    Separate routing proprietary components

            beforeEnter

    3.3.4 Vue-Router Components

    Vue is used to write routes to a plug-in. The router – the link, the router – the view

    3.3.5 Vue – the Router

    Same as above, I recommend my article:

    Brief introduction to some advanced uses of vue-Router

    Brief introduction to the use of VUe-Router and dynamic routing and nested routine

    conclusion

    You can see here and thank you very much, after all can see my Lao comrade so long, is also a recognition of my this article, in addition don’t advice to a praise with a focus on, or thank you, new creation, after all, it is not easy, just typing all in a day, so hope you much attention, reviews and thumb up, it’s better if have forwarded.

    In addition, what I wrote is not in place, I hope you are the gods in the comments area criticism, thank you.

    In addition, the article will be updated every week to two weeks. Please forgive me. Recently, I am busy and can only update every other week, and I will update every week if I have enough time.