Vue2 technology finishing 3 – Advanced chapter – update completed

Time:2022-5-27

3. Advanced chapter

preface

3.1. Custom events of components

3.1.1. Binding custom events
  • There are two implementation methods here: one is to use v-on with vuecomponent$ Emit implementation [PS: this method is a little similar to passing from child to parent]; The other is to use ref attribute and mounted () to implement [this method: a little more complex, but more flexible]
  • Both methods can be implemented, and the difference between them is very similar to that between computed and watch [PS: the second method can realize asynchronous operation, such as event binding after Ajax sends a request to get data]. Next, let’s look at examples to understand more clearly, In the traditional way, you can pass a parent-child parameter to the parent-child, but pass it to the parent-child first

image

3.1.1.1 v-on collocation$emitrealization

image

image

image

  • V-on can be abbreviated!!!!

3.1.1.2 implementation of ref with mounted
  • Based on the previous implementation, the sub component code remains unchanged, and the following code is added to the parent component

image

image

  • Asynchronous operations can be performed in mounted (), so this custom event can be made more flexible

  • In addition, since it is an event, you can also use event modifiers: prevent, stop, once

    • In v-on, the three play the same way as before, which can be added after the event name, such as:@zixeiqing.once = "xxxxx"
    • In ref, it is used inthis.$refs.person.$on('zixieqing',this.demo )Medium$onHere, once is used$once, replace the original$on

3.1.2. Unbinding user-defined events
  • This thing usesVueComponent.$off( ['EventName'] )This built-in function is used to unbind,
    • Of course: if a single event is unbound in the array [], the bracket [] is OK;
    • If it is to unbind multiple user-defined events, use commas to separate them;
    • In addition:$off()When parameters are not passed, all custom events of the component are unbound by default [PS: one unbound one]
    • The core words of user-defined events: the event is bound to who; Unbind custom events to whoever you unbind them to

image

  • In addition: when playing beforedestroy of Vue life cycle, I just mentioned one small point briefly. The life cycle diagram is as follows

image

  • The last point in the above figure is not verified:

image

In beforedestroy, subcomponents and custom events are destroyed

  • Say to destroy the custom event at this time

image

image

  • The so-called destruction of child components is easy to understand, that is, after the parent component is destroyed, the child component will not survive [PS: if you want to verify, you can use the destruction VM, and then see if its child components can survive? The answer is definitely not alive]

3.1.3. Two pits in user-defined events

The subcomponents look like the following

  • image

1. In the implementation of ref attribute, there is a problem about the direction of this

  • The first is to put the callback function into the methods of the parent component
    • image
    • image
    • In this way, you will find that this refers to the parent component
  • The second method: put the callback function directly into thethis.$refs.people.$on( 'event',xxxx ) ]In XXXX
    • image
    • image
    • In this case, it will be found that this is no longer the instance object of the parent component, but the instance object of the child component, but it can be changed into the instance object of the parent component [PS: write the ordinary function of the callback into lambda expression]
      • image
      • image

2. The pit where components use native DOM events [PS: understand the native modifier. When people who learn from the back end read the source code, they can’t be more familiar with this modifier]

  • image
  • image
  • image
  • image

3.1.4. User defined event summary
  • Custom event is a way of communication between components, which is applicable to: child component – > parent component communication

  • Usage scenario: when you want a child component to pass data to the parent component, bind custom events to the child component in the parent component [PS: event callback in parent component methods / other places], and find the child component itself to unbind the custom events

  • Bind custom events:

    • 1. In the parent component:or

    • 2. In the parent component:

      • .........
        methods: {
        	test(){......}
        }
        	.........
        mounted(){
        	this.$refs.demo.$on('eventName',this.test)
        }
    • 3. If you want a custom event to be triggered only once, you can use the once modifier [PS: the one implemented using v-on] or $once [PS: the one implemented using ref attribute]

  • Trigger custom event:this.$emit('eventName',sendData)[PS: ask the person who binds the custom event to trigger it]

  • Unbind custom event:this.$off(['eventName',.......])[PS: unbind the user-defined event to whom you bind it; also: note that unbinding events are written in a single, multiple and complete way]

  • The DOM event of the element can also be bound on the component, but: the native modifier needs to be used

  • Note: passedthis.$ refs. xxxx.$ On ('eventname ', callback)When Binding custom events, the callback is either configured in the methods of the parent component, or use the lambda expression [PS: or arrow function], otherwise: there will be problems in the execution of this

3.2. Global event bus

  • This thing is not a knowledge point, but a skill used in development. The knowledge contained in it has been played before, but: the knowledge has been skillfully applied,Change the custom event and add a built-in relationship in VueVueComponent.prototype._ _proto _ _ === Vue.prototypeSo as to realize a development skill
  • This skill: communication between any components can be realized
3.2.1 clear the logic of global event bus

image

But: now change your mind and realize it

image

After understanding the above analysis diagram, it can be analyzed that the separately selected component needs to have the following characteristics:

  • 1. This component can be seen by all components
  • 2. This component can call$on()$emit()$off()

1. So in order to achieve the first step: what can be done to make all components visible?

  • 1) . it can be achieved by using window object (but it is not recommended)
    • image
    • image
    • image
    • This method is not recommended because it is originally a framework. Who wants to put something on the window? Isn’t it looking for trouble
  • 2. Is to take advantage of the built-in relationships in VueVueComponent.prototype._ _proto _ _ === Vue.prototypeThat is, the common component is selected as the Vue instance object VM, the origin of this relationship is not explained here. It has been explained in the basic chapter vuecomponent(),Using this built-in relationship is to use vuecomponent to obtain the properties and methods on the Vue prototype. At the same time, after selecting the Vue instance object,$on()$emit()$off()You can call them all. These functions are built-in functions of Vue. Haven’t these functions been used for Vue instance objects yet

3.2.2 global event bus instance
  • Implementation method:VM + beforecreate() [PS: initialize, let the relationship be established at the beginning] + mounted() + $on() + $emit() + beforedestroy() [PS: finish work, unbind custom events] + $off()

Example demonstration:

  • image
    • Note: in the figure above$busIt’s your own name, but it’s generally used in development. Bus bus can be used by anyone, and it can also carry many people. It’s put into the component: anyone can access it. Add one$Because it caters to Vue’s design and built-in functions, pretending that it was not designed by the programmer [PS: in fact, bus also means bus]
  • image
  • image
  • image

3.2.3 summary of global event bus
  • Global event bus, also known as globaleventbus

  • It is a communication mode between components and can be applied to any communication between components

  • How to play the global event bus:

    • 1. Install global event bus

      • new Vue({
                .......
                beforeCreate(){
                    Vue.prototype.$bus = this
                },
                ......
            })
    • 2. Use event bus

      • Send data:this.$bus.$emit('EventName',sendData)

      • Receive data: if component a wants to receive data, bind a custom event to $bus in component A and put the callback of the event into component a itself [PS: get data by callback]

        • //You can also use methods; No, you can also put the callback in $on() [PS: it is recommended to use methods, because you don't have to consider this problem in $on()]
              methods: {
                  sendData(){ ...... }
              },
              ........
              mounted(){
                  this.$bus.$on('eventName',receiveData)
              },
              .......
              beforeDestroy(){
                  this.$bus.$off([ 'eventName' , ..... ])
              }

3.3. News subscription and publication

What is message subscription and publishing?

  • This thing is seen every day, that is: pay attention to people. If others send a notice / article, they can receive it. This is subscription and publishing
  • Here we use the library PubSub JS to demonstrate (it’s OK to use other libraries. The idea of these gadgets is the same. This is a third-party library, not Vue its own), where:
    • Pub means publish, which means push and publish
    • Sub means subscribe
    • That is: one party publishes and one party subscribes. This thing is familiar to people playing at the back end. There are message subscription and publishing in redis, and the instructions are both these two words. Rabbitmq is the same routine, but it is more complex
3.3.1. Play PubSub JS

Basic code

  • image
  • image

1. Install PubSub JS library for the project. Instruction: NPM install PubSub JS

  • image

2. Message publisher

  • 2.1. Import PubSub JS Library

  • 2.2. Use the API publish (‘msgname ‘, SendData) to send data

    • image

3. Message receiver

  • 3.1. Import PubSub JS Library
  • 3.2. Use the API subscribe (‘msgname ‘, callback) to receive data through callback
  • 3.3. Close subscription
    • image

4. The effect is as follows

  • image

3.3.2 summary of news subscription and publication
  • It is a way of communication between components, which is suitable for communication between any components

  • Use steps:

    • 1. Install PubSub JS command:npm install pubsub-js

    • 2. The message receiver and sender should introduce PubSub codeimport pubsub from "pubsub-js"

      • Data sender:pubsub.publish('msgName',sendData)

      • Data receiver:

        • //Methods can be written or not [PS: it is recommended to write, without considering the direction of this, which is the same as that of user-defined events]
          methods: {
          	demo(){.....}
          }
          ........
          mounted(){
          	//Use this Msgname ties each subscription to the component instance object VC to facilitate obtaining the subscription ID when canceling the subscription
          	this. msgName = pubsub. subscribe('msgName', callback) 	//  If you don't write methods, the callback will be written here. Note: use the arrow function
          }
          .......
          beforeDestroy(){
          	pubsub.unsubscribe( this.msgName )
          }

3.4 slot

1. Basic code

  • image
  • image
  • image

3.4.1. Default slot
  • This slot is suitable for occupying only one position

Demand, let the food classification show a specific food picture, let the film classification show a specific film, and use the default slot

  • image

  • {{game}}
              
            
    
            
              
            
          
        
    
        
        import Category from "./components/Category.vue"
          export default {
            name: 'App',
            components: {Category},
            data() {
              return {
                Foods: ['laver', 'Orleans roast wings',' all kinds of mousse ',' Black Forest ',' Brownie ',' tiramisu ',' steak ',' cooked sushi '],
                Games: ['glory of the king', 'peace elite', 'League of heroes',' civilization and conquest ',' boxing emperor ',' QQ flying car ',' Warcraft '],
                Files: ['Infernal Affairs',' equator ',' confinement island ',' Chinatown detective 1 ',' Shawshank Redemption ',' inception ',' unparalleled ']
              }
            },
          }
        
    
        
          .container {
            display: flex;
            justify-content: space-around;
          }
    
          img,video {
            width: 100%;
          }
  • image

3.4.2 named slot
  • It refers to the slot with a specific name, which is two steps more than the default slot
  • When slot is used for space occupation, use the name attribute to give a name, and then use the slot = “XXX” attribute to specify which slot the structure content is inserted into when passing the structure

Demand, show “hot” and “suspense” at the bottom of the movie category

  • image
  • image
  • image

3.4.3 scope slot
  • The playing method of this gadget is similar to that of a named slot, except that it has a little more steps, a more requirement, and the problem to be solved can be reversed

Basic code

  • image
  • image
  • image

Requirements: when multiple components are used together, the data is the same, but there are the following requirements:

  • When displaying data, it is required not to be all unordered lists, but also sequence tables and H tags
  • The data is required to be in the sub component [PS: in category], and the structure needs to be written in the parent component [PS: in app], that is, the parent component needs to get the data in the sub component
  • Using the child parent component communication mode that has been played before can be done, but it is troublesome. Therefore: modification code

Start modification code:

  • Step 1: data extraction
    • image
    • View effect:
      • image
      • You may think: you can obviously put data into the parent component / structure UL into the child component to achieve the effect. Why do you have to toss like the above and find something to do? Sometimes in development, others will not give you the data. They just give you a way so that you can get it
  • Step 2: use the scope slot for transformation
    • image
    • image
    • image
    • image

Since the scope slot can play, implement the requirements

  • image
  • image
  • image

In addition, another way to write the scope when the parent component receives data is to use slot scope

  • image

3.4.4 slot summary

1. Function: enables the parent component to insert HTML structure into the specified position of the child component. It is also a way of communication between components. It is applicable to:Parent component = = = child component

2. Category: default slot, named slot, scope slot

3. Mode of use

  • 1) . default slot

    • //Parent component
          
              
                  html structure 
              
          
      
          //Subcomponents
          
              
                  
                  Slot default content
  • 2) . named slot

    • //Parent component
          
              
              You can also add another HTML structure
          
      
      
      
          //Subcomponents
          
              
                  
                  Slot default content
  • 3) , scope slot

    • //Subcomponents
          
            
                {{Title}} classification
                
                This is the default
            
          
      
          
              export default {
                  name: 'Category',
                  props: ['title'],
                  Data() {// the data is in the subcomponent itself
                      return {
                          Files: ['Infernal Affairs',' equator ',' confinement island ',' Chinatown detective 1 ',' Shawshank Redemption ',' inception ',' unparalleled ']
                      }
                  },
              }
          
      
      
          //Parent component
          
            
              
                
                 
                   
                   
                   
                     {{filem}}
                   
                 
              
      
              
                
                 
                   
                     {{filem}}
                   
                 
              
      
              
                
                 
                    {{filem}}
                 
              
      
              
              
                
                 
                    {{filem}}
                 
              
            
          
      
          
          import Category from "./components/Category.vue"
            export default {
              name: 'App',
              components: {Category},
            }

3.5、Vuex

  • Concept: in Vue instance, a plug-in for centralized state (data, state and data are equivalent) management. In a popular way, it is data sharing,Read / write the same data between multiple components, isn’t it centralized management (the opposite view is “distributed”. Java learners are most familiar with why there is distributed management
  • GitHub address:https://github.com/vuejs/vuexOn the official website, there is vuex in the ecology of Vue official website
  • When to use vuex?
    • 1. Multiple components depend on the same state (data) [PS: two handsome guys want the same pretty girl]
    • 2. The behavior of different components needs to change the same state [PS: two girls in foot washing city want to change the money in the customer’s wallet into their own pocket]
    • 3. The above is summarized in one sentence:Vuex is used when multiple components need to share data

3.5.1 vuex principle
  • First of all, this thing is available on the official website, but: not all

image

  • So: change the original picture of the official website
    • image
    • The above content is only a general understanding of the schematic diagram. Next, we will understand it step by step through the code demonstration

3.5.2 setting up vuex environment

1. Install vuex in project Directive: ‘NPM install vuex’

2. Write store

  • image

3. Make the store available in any component

  • image
  • image
  • In this way, the store will naturally appear on other components [PS: it uses the built-in relationship between VC and VM to verify itself, and you can see it by outputting this in other components]

Summary of vuex environment construction

  • 1. Create the file Src / store / index js

    • //Introduce vuex
          import vuex from "vuex"
      
          //Using vuex -- Vue is required, so Vue is introduced
          import Vue from "vue"
          Vue.use(vuex)
      
      
          //Create three things in the store: actions, changes and state
          const actions = {}
      
          const mutations = {}
      
          const state = {}
      
          //Creating a store -- the same routine as creating a Vue
          export default new vuex.Store({
              //Incoming configuration items - store is the manager of actions, changes and state, so configuration items are them
              Actions, // full writing method actions: actions is an object, so it can be abbreviated
              mutations,state
          })
  • 2. In main Configure store in JS

    • import App from "./App.vue"
          import Vue from "vue"
      
          //Introducing store
          import store from "./store"     
          //Because the name is index, so only write/ Store is enough. In this way, the default is to find the index. If there is no index, an error will be reported
      
          const vm = new Vue({
              render: h=>h(App),
              components: {App},
              //Enable the store to be seen by any component -- add it to the VM configuration item [PS: similar to the global event bus]
              store,
              template: ``,
          }).$mount('#app')

3.5.3. Simply play vuex
  • According to the schematic diagram

1. First put the data to be operated / shared data into the state

  • image
  • image

2. Use the API dispatch in the component to pass the key value to actions [PS: dispatch is familiar to Java learners, dispatcherservlet, the central brain of spring MVC]

  • image
  • Actions is the first level of processing [PS: Waiter]
  • image

2. Actions receive key value [PS: if there is a logical operation, put it here, and so is Ajax]

  • This is to call the commit API and pass the key value to the mutation, which is the person who really works [PS: the kitchen man]
  • image
  • image

3. Changes receive key value

  • image
  • image
  • image
  • image

4. View developer tools [PS: simple understanding, self-help]

  • In addition, if the version of vuejs devtools development tool is different, the page layout is also different, but the function is the same

  • image

Of course: as mentioned earlier, it is possible to call the API commit directly in the component to deal with changes. This is applicable to processes that do not require logical operations. The example will be completed by itself

The above is a simple understanding of vuex. The previous examples seem useless, but vuex is actually very easy to use

3.5.4 know getters configuration item
  • This thing is the same as the relationship between data and computed
  • image
  • image
  • image

3.5.5. Four map methods
3.5.5.1 mapstate and mapgetters

image

1. Transforming source code — using computational properties

  • image
  • image
  • But: we write the above calculation attributes by ourselves, and vuex has provided something to help us automatically generate the things in the calculation attributes, which can be done in one sentence of code

2. Use mapstate transformation to obtain the data in state, so as to generate calculation properties

  • 1. Introduce mapstate Code:import {mapState} from "vuex"
  • 2. Use mapstate [PS: object writing]
    • image
    • image
  • 3. Array writing method [PS: one recommended]
    • ...mapState({sum:'sum'})What’s in heresum:'sum'These two are the same,So: one multi-purpose
    • image
    • image

3. Use mapgetters to generate things in getters into computational properties

  • 1. Introduce mapgetters Code:import {mapState,mapGetters} from "vuex"
  • 2. Use mapgetters [PS: same as mapstate, object writing]
    • image
    • image
  • 3. Array writing
    • image

3.5.5.2 mapactions and mapmutations
  • If you know mapstate, you will know other map methods as well. It’s almost the same, but the principle is to adjust different APIs. Of course, you will also pay attention to it
  • Mapstate and mapgetters are generated in computed, while mapactions and mapmutations are generated in methods

1. Mapactions — the API of the call is dispatch

image

  • Transform with mapactions
    • 1. Import mapactions Code:import {mapActions} from 'vuex'
    • 2. Use mapactions [PS: object writing] – prepare to transfer into the pit
      • image
      • image
      • reason:
        • image
        • image
    • 3. Array writing method — the same, the function name is the same as the name in actions [PS: one name for multiple purposes]
      • image
      • image

2. Mapmutations – this is exactly the same as mapactions, except that the API called is commit

  • image
  • So: this method is not demonstrated. If you can use any of the above three methods, you will get this

3.5.6. Simply play with components to share data

1. Add a little more shared data in state

  • image

2. Add person component

  • image
  • image
  • image

3. Shared data

  • Get person in the count component and count in person [PS: this step will not be demonstrated. If you know the former, the latter will]

The operation is as follows:

  • image
  • image

3.6 router

3.6.1 understanding routing and router
  • Routing: a set of key value mapping relationshipsThat is, route
    • Key is the path in the website
    • Value is a function or component
      • Function is because of the back-end routing (the back-end calling function responds to the request of the path)
      • There is no need to say more about component components
  • Router: it is specially used to manage routing [PS: if you understand, refer to the router in life. There are many jacks behind it, and then it can be linked to the TV. The jack is the key, and the linked TV is the value]
  • In Vue, router is a plug-in library, so it needs to be usednpm install vue-routerTo install, this thing is specially used for single page website applications
  • The so-called single page website application is spa, that is, only operate in one page and the path address changes, and then display the corresponding things to the current page without opening a new tab [refer to meituan website and click to see the address, page update, whether a new tab is opened, and meituan is a single page website application]
    • The whole application of spa onlyA complete pageClick the navigation link in the pageThe page will not be refreshed, only the pageLocal refresh. data needs to be obtained through Ajax request

3.6.2. Simple use of router

1. Preparation:

  • 1) . introduce bootstrap css
    • image

2. Start playing router

  • 1) Install routing instructions for the project:npm install vue-router

  • 2) , in main Introduce and use router in JS [PS: router is a plug-in]

    • image
  • 3) . writing components

    • image
  • 4) Configure the router [PS: This is also called configuring routing rules, which is in the form of key value. In the front end, key is the path and value is the component]

    • image
  • 5) . introduce the configured routing rules into main JS

    • image
  • 6) Use routing in static pages[PS: two labels need to be rememberedand ]

    • It refers to: jump, where: the path name is the path configured in the routing rules. It is understood by referring to the a tag, which is essentially converted to the a tag

    • It means that the view display is to tell the router where the component configured in the routing rules should be displayed, which is the same as the slot

    • image

    • The source code of the page structure is as follows:

      • Vue Router Demo 
                  
                
                
                  
                    
                      About
                      Home
                      
                    
                  
                  
                    
                      
                        
                      
                    
                  
                
              
            
        
            
              export default {
                name: 'App',
              }
  • 7) The operation effect is as follows:

    • image

In addition: from here on, you can first explore the element UI component library. This is a website and bootstrap specially matched with Vue to make pages. This thing will be used later. The website is as follows:

Summary of Vue router usage

  • 1. Install Vue router, command:npm install vue-router

  • 2. In main Instructions in JS:import VueRouter from "vue-router"

  • 3. Apply Vue router plug-in, instruction:Vue.use(VueRouter)

  • 4. Write router routing rules

    • //Introduction router
          import VueRouter from "vue-router"
          //Introduce components that need to jump to page content
          import About from "../components/About.vue"
          import Home from "../components/Home.vue"
      
          //Create and expose routers
          export default new VueRouter({
              Routes: [// routers manage many routes, so: routes is an array
                  {// each route in the array is an object, which has two configuration items: key and value [PS: and others]
                      Path: '/ about', // is the key, that is, the path name, for example: www.baidu.com COM / about about here
                      Component: about // is value, that is, component
                  },{
                      path: '/home',
                      component: Home
                  },
              ]
          })
  • 5. Achieve switching (active class configurable highlight style)

    • About
  • 6. Specify display location

3.6.3. Talk about some details of the router
  • 1. In the future, routing components will be placed in the page folder, while general components will be placed in components
  • 2. During route switching, the “hidden” routing components are destroyed by default and re mounted when necessary [PS: example: self test through beforedestroy and mounted]
    • image
  • 3. Each component has its own$routeProperty, which stores its own routing information
    • image
    • image
  • 4. There is only one router in the whole application, which can be through the component$routerGet the attribute [PS: verify that you bind this thing of different components to the window object by yourself, and then get them for comparison after the routing components are mounted. The answer is: false]
    • image

3.6.4 multi level routing

1. Create two new routing components under Src / page

  • image

2. Write multi-level routing for home routing rules

  • image

3. Rewrite hmoe Vue routing component

  • image

  • The source code is as follows:

    • I am the content of home
                  
                      
                          
                              
                              News
                          
                          
                              Message
                          
                      
                      
                          
                      
                  
              
          
      
          
              export default {
                  name: 'Home'
              }

4. The operation effect is as follows

  • image

3.6.5 routing parameters

1. String parameter passing method of query [PS: that is, path parameter passing, suitable for passing a small number of parameters]

  • 1) Write data and transform message Vue routing component [PS: data sender]
    • image
  • 2) Write detail Vue routing component [PS: data receiver]
    • image
  • 3) . write routing rules
    • image
  • 4) The effects are as follows:
    • image

2. Query object writing [PS: suitable for passing a large number of parameters

  • image
  • The operation effect is the same
    • image

3.6.6 named route
  • This thing is to deal with the long string in the path, which is equivalent to an alias

example:

  • 1) . modify routing rules
    • image
  • 2) Use named route to simplify path
    • image
  • 3) The operation effect is as follows
    • image

Named route summary

  • Function: simplify the path writing method during route jump

  • use:

    • Name the command

      • {
                    path: '/home',
                    component: Home,
                    children: [
                        {
                            path: 'news',
                            component: News
                        },{
                            path: 'message',
                            component: Message,
                            children: [
                                {
                                    path: 'detail',
                                    //Name the route with another configuration item name, which makes the path more compact
                                    name: 'detail',
                                    component: Detail
                                }
                            ]
                        },
                    ]
                },
    • Simplified route jump writing method

      • {{m.title}}
                      
        
        		
        			
                        {{m.title}}

3.6.7 routing another parameter – params
  • Note: this parameter transfer must be based on the name configuration item, which will be explained later
  • In addition, this kind of parameter transfer is the restful parameter transfer in the back end

1. Params is used to pass the parameter [PS: Data transferor]. This step is no different from the previous query transfer, but the name is changed

  • 1) , string writing / object writing
    • image
  • 2) . modify routing rules
    • image
  • 3) . get parameters [PS: compared with query, the data storage location has changed a little. You can output this. $route in mounted to see the structure]
    • image
  • 4) The effect is as follows
    • image

Summary of params routing parameters

  • 1. Configure routing

    • {
                  path: '/home',
                  component: Home,
                  children: [
                      {
                          path: 'news',
                          component: News
                      },{
                          path: 'message',
                          component: Message,
                          children: [
                              {
                                  //If params is used to transfer parameters, the rule of path needs to be changed, that is, the occupation and the corresponding parameters
                                  path: 'detail/:id/:title',
                                  Name: 'detail', // object writing method. This configuration item must be guaranteed
                                  component: Detail
                              }
                          ]
                      },
                  ]
              },
  • 2. Transfer parameters

    • {{m.title}}
                    
      
      		
      			
                      {{m.title}}
    • Note: when the route carries params parameters, if the object writing method of to is used, the path configuration item cannot be used, but the name configuration item must be used

  • 3. Receive parameters

    • {{$route.params.id}}
      	{{$route.params.title}}

3.6.8 props configuration item of routing
  • Props has been seen in the parent-child communication of components, but it is not the same thing. It is between components. Now it is routing, and the writing method is almost different
  • There is a saying here: props is configured in which routing rule which routing component wants to receive data
  • Back to the question: the interpolation syntax is about simple template syntax, but not the one shown in the figure below, so it should be simplified
    • image

1. Boolean writing

  • When it is true, all params parameters received by path are sent to the required routing components in the form of props, e.g. detail here

    • Note: it is a parameter passed by params, so this is one of the disadvantages
    • In addition, it is transmitted to the required components in the form of props, so the required routing components need to use Pros: [‘xxxx ‘] to receive, so that the use of data in the required components can be simplified
  • image

2. Function writing

  • This way of writing: it is the most flexible one,When props is a function, each set of key values in the object returned by the function will be transmitted to the routing component of the required data through props [PS: such as the detail here]
    • In this way, you can get the data passed by query and also receive the data passed by params. Note that you can change the name when calling in the function
    • The advantages of this method are: first, both query and params can be received; second, the logic of data reception is written into the routing rules of the routing component to receive data, which makes the logic clearer and avoids looking for Logic Codes everywhere
  • image

3. Another way

  • Another method is not recommended, so: simply understand it
  • 1) . extract the code from the data user to form the calculation attribute [PS: for example, the detail routing component in the example is troublesome in the interpolation syntax when fetching data, so configure the calculation attribute below to extract the code, but: add to the snake, because it will be used when fetching data in the calculation attributethis.$route.queru / params.xxxxIf the amount of code is large, don’t you have to write more N and this
  • 2) . object writing method – you don’t need to know that there is such a thing, and you can baidu yourself when you need it [PS: this thing receives data is dead, and it’s basically not used in development]
    • In this way, the combination of all key values in the object is finally transmitted to the required routing component through props

3.6.9 replace attribute in router link

image

  • The above mode is the push mode. Its principle is stack space, pressing stack and pushing【PS: the default mode in router link is push mode
    • image
  • However, there is another mode: replace mode. This mode is to kill the last record after generating a record, so the effect is that there will be no back record, and the back button can’t be clicked [PS: it’s a short way, there’s no way back ^ ^ ^. To realize this mode, it’s also simple: add a replace attribute in the router link]
    • image
    • In this way, when you click home / about again, its history will not be left
      • image

Summary of replace attribute of router link

  • Function: control the mode of operating browser history during route jump
  • There are two ways to write the history of the browser:pushandreplace, where:pushIs to add history,replaceYes to replace the current record. The default is when the route jumpspush
  • How to enable replace mode:News

3.6.10 programming route navigation
  • This thing is no longer usedrouter-linkTo achieve routing jump, play in front$route, and now I’m here to play$router
  • Have a look first$routerThis thing, by the way, knows which APIs to master, which are the five in the figure below
    • image

1. Play with the push and replace APIs

  • The principle of push and replace is as mentioned above. One keeps the history record and the other clears the last history record
  • image
  • image

2. Play back and forward APIs

  • These two are forward and backward in the browser
  • image
  • image

3. Play go API

  • Positive and negative numbers can be used in go (). Positive numbers mean: advance the filled number step; A negative number is the absolute value of the number you fill in
  • image
  • image

3.6.11 cache routing component
  • The foregoing is not to say that the routing component will be destroyed after being switched. Therefore, this situation will lead to that sometimes the data in a routing component should not be destroyed, but retained. Therefore, we need to use the knowledge points to be explained, that is, we use oneTag

1. Cache a routing component — string writing

  • image
  • image
  • image
  • To facilitate verification, add the following code
    • image
    • image

2. Cache multiple routing components — array writing

  • image
  • I won’t do the demonstration

3.6.12. Other life hooks
  • In the basic chapter, it was said that in addition to the eight life hooks [PS: 4 pairs], there are actually three life hooks that haven’t been played. It was also said that they can be adjusted after routing

1. Another pair of life hooks

  • This pair of life hooks are activated and deactivated, where:
    • Activated is activated [PS: I want to see you, just tune it]
    • Deactivated is inactivated [PS: I don’t want to see you anymore. Just leave and adjust it. It’s a bit similar to the hook before destruction, but: the handling is different]
    • Applicable scenario: used in advancekeep-alive include = "xxx"Keep the modified components and don’t let them be destroyed after switching [PS: beforedestroy doesn’t work], then you can use these two hook functions if you want to finally turn off the timer and so on
  • example:
    • image
    • image

2. Another hook function is nexttick

  • This thing is not demonstrated. It is to make the time difference during parsing, because some things need to insert the appearance after parsing into the page before they can continue to do other things. Therefore, nexttick can be used, so that some templates can be parsed and put into the page first, and then some of the following things can be parsed to execute some of the logic we want, such as the input box, When I render the input to the page, the focus of my mouse is in the input box, so I can use this hook function to call this hook when mounting, and then put the logic of cursor focus into the nexttick callback
  • Nexttick hook plays on the official website. You can understand it at a glance
    • image

3.6.13 route guard – important and commonly used in development
  • The so-called route guard is the issue of permissions, that is, what permissions can you access
3.6.13.1 global pre routing guard
  • **One of the characteristics of the so-called global pre routing guard is reflected in the word pre. Its API is beforeeach ((to, from, next) = > {}), that is, the callback will be called before route switching / initialization, and the callback will be called during rendering**
  • example:
    • image
    • image
    • It’s inconvenient to demonstrate, so to is the component location after switching the routing component [PS: where to go, target component]; And from is the component location before switching the routing component [PS: where to come from and which routing component to come from]; In addition, next is a function next (), which means release
  • Now do an operation, cache a key value in the browser, and then judge whether the key value is right when accessing the news and message routes. If it is right, the corresponding routing components will be displayed. Otherwise, it will not be displayed
    • image
    • image
    • Play a little game
      • image
  • Of course: there is a trick to simplify the previous process
    • image
  • Add a meta configuration item to the routing rule, which is the routing metadata. With this configuration item, we can put something we want to put into the route [PS: add a meta configuration item to any route that needs permission verification], so let’s transform it
    • image
    • image
    • image

3.6.13.2. Global post routing guard
  • This is the opposite of the global pre routing guard, but the processing scenario is different
  • The API called by the global post routing guard is aftereach ((to, from) = > {}). Note: compared with the global pre routing guard, the next parameter is missing. The post routing guard has already judged the permission in the front. Why do you still consider whether to release it? What the global post routing guard does is not to judge the permission, but to finish, and do some judgment after passing the permission, For example: after clicking a routing component, as long as the content of the component can be viewed, the page tab title will be changed
  • This API is called when initializing rendering / after routing component switching,
  • example:

    • image
    • Practice first hand: [PS: use pure global pre routing guard first]
      • Put something in first
        • image
      • image
      • image
      • It looks successful, but there are bugs. You can try to adjust the network in the network to slow 3G. You can see the effect slightly clearly. If you want to change it successfully, you can even change the public / index in the project If the title of HTML is changed, it is the same. There will be a loading process. Therefore, there is no way to change the flower in order to achieve the desired effect in the global pre routing guard. Moreover, it is not standard to write the same code twice in the global pre routing guard
        • image
        • image

  • If you want to achieve the above effect, you need the global post routing guard to come on stage. Drop the API and finish it with one line of code
    • image
    • The effect will not be demonstrated, and the effect has been achieved [PS: note that the title in public / index.html should be changed to ‘big data smart cloud generation platform’, otherwise there is a loading process when accessing the root directory. This is not the pot of this knowledge point, because the title of the native public / index.html is the name in the second line of the read package.json]

3.6.13.3 exclusive route guard
  • This refers to the exclusive route guard of a route. The API called is: beforeenter ((to, from, next) = > {}). It means that the callback will be called before entering the route configuring this API. Among them, the meaning of “to”, “from” and “next” is the same as that of the previous global pre route guard, but note: there is no post, and it has only one pre, that is, the exclusive route guard
  • Finally: the routing guards can be matched at will
  • example:
    • image
    • image

3.6.14 two working modes of router
  • The two modes are hash and history
    • Default mode of hash routerThere is a # in the path. The content behind this # does not need to be transmitted to the server along with HTTP, and the server will not receive [PS: just play at the front end]. Note: what are the differences between this hash algorithm and the hash algorithm in the back end? Don’t get confused
      • image
    • History modeThis is easy to understand. Without that #, things after IP: port in the path will be transmitted to the server along with HTTP
  • Differences between hash and history modes:
    • 1. There is # in the hash mode path, and the content after # will not be transmitted to the server with HTTP; While there is no # IP: port in the history mode path, things after it will be transmitted to the server along with HTTP
    • 2. The compatibility of hash mode is good, while the compatibility of history mode is slightly poor
  • You can add two new routing rules in history and history
    • image

3.6.15. Questions about the launch of the project
  • This is because there is another difference between hash and history mentioned earlier. There is a pit / attention point when going online

1. Package the project after programming

  • The project has been started withnpm run serve, it was said at the scaffold that there was another order:npm run buildAt that time, it was said that the front resource of the back end is HTML + CSS + JS, so it is needed for project packaging at this time
  • First switch the working mode of the router to history mode, and then package it, so as to facilitate the demonstration of bugs
    • image
    • image

2. Use the node + Express framework to write a small server to simulate the launch

  • Create a new folder by yourself and open it with vscode

  • 1) . make the folder a legal package instruction:npm init

    • image
  • 2) . instructions for installing express:npm install express Note: this step is very easy. If you don’t have enough permissions due to improper operation when configuring nodejs, you will report a pile of warnings and errors

    • image
  • 3) . create a new JS file with the following contents

    • image

    • The source code is as follows:

      • //1. Introduce express. Note: This is not the modularization of ES6, but the modularization of commonjs
            const express = require('express')
        
            //2. Create an app service instance object
            const app = express()
        
            //3. Port number monitoring
            app. Listen (8001, (ERR) = > {// err is an error object
                if( !err ) console. Log ("server started successfully");
            })
        
            //4. Configure a back-end route
            app. Get ('/ person', (req, RES) = > {// req is request and res is response
                res.send({
                    Name: 'Purple evil feeling',
                    age: 18
                })
            })
    • 4) . instructions for starting the server:node server

      • image
    • 5) Access the port in the server and test it

      • image

3. The preparatory work is finished. Now put it into usenpm run buildCopy the files in the packed dist to the server

  • Create a new static / public folder in the server [PS: people at the back end of these two folders are familiar with them, that is, the two in springboot. I won’t explain here. Either of these two folder keys can be used]
  • image

4. So that the copied files can be recognized by the server

  • image
  • Re executenode serverStart to demonstrate another pit of the two working modes of the router [PS: don’t forget to have a permission authentication. Put the corresponding things in the cache, otherwise some routing components can’t click]
    • image
    • Fix the bug. After clicking some routing components, refresh the page [PS: just make sure the path is not localhost: 8001, and there is something behind it]
      • image
      • This is the pit of the history mode, but this will not happen when switching to hash. The reason for the above situation is that we just clicked the routing component in the page, and there are pages because: those are static pages, and those data and history records are original, that is, they do not go through the network request, but after refreshing, they go through the network request, It will send things after IP: port in the path to the server along with HTTP. It goes to the server to find resourceshttp://localhost:8001/home/news/ home / news in the server. There is this resource in the server, so: 404
      • If you want the history mode to be the same as the hash mode, you need to find the back-end personnel to deal with the refresh without error. The back-end personnel need to cooperate with you to take the past resources. There are many ways to deal with this problem in the back-end, such as nginx [PS: but sometimes others throw you a hammer, and the final code problem is just your own back], so: to solve it by yourself, you need to use a plug-in connect history API fallback
        • image
        • image
        • image
        • image
        • image

3.7 conclusion

This concludes vue2. There are also some Vue UI component libraries

The next point is vue3 technology