A deeper understanding of the basics of Vue

Two important little principles

  1. The functions managed by Vue are best written as ordinary functions, so that this points to the vm or component object
  2. For all functions not managed by Vue (timer callback function, ajax callback function, Promise callback function), it is best to write arrow functions, so that this points to the vm or component instance object

 

1. The difference between computed properties and methods

       1. In vue template rendering, when a method is bound to an element, the method will be executed every time the template is rendered, because the method is not cached. The difference is that the computed computed property has a cache function, that is, when you bind a computed property to an element, since the computed property has a cache function, every time the template is rendered, the computed property will not be re-executed, but It is to find the cache of this computed attribute, and only when the attribute that the computed attribute depends on changes, will the attribute be re-executed.

        2. Since the return value of the calculated property is calculated and returned through the existing property, because of this special nature, the calculated property cannot perform some asynchronous operations. as follows:

       

         3. Computed can be completed, watch can be completed

         4. Computed may not be able to complete what watch can complete. For example, watch can perform asynchronous operations

1.1 Complete writing of computed properties

        Each computed property has two methods, get() and set(), written in detail as follows:

    computed: {
      fullName: {
        get(){
          console.log('get被调用了')
          return this.firstName + '-' + this.lastName;
        },
        set(value){
          console.log('set被调用了');
          const str=value;
          str=value.split('-')
          this.firstName=str[0];
          this.lastName=str[1]
        }
      }
    }

       When the calculation data you use only considers reading and does not consider modification, you can use the shorthand method:

computed:{
  fullName(){
    console.log('get被调用了')
          return this.firstName + '-' + this.lastName;
  }
}

So, in the computed property, when do get and set start to be called?

  • get: When someone reads the calculated property fullName , get will be called, and the return value will be used as the value of fullName
  • set: When the fullName is read for the first time, when the dependent data changes

1.2 Relevant instructions for computing properties

  1. Definition: The attribute to be used does not exist and needs to be calculated from existing attributes
  2. Principle: Provide getter and setter with the help of Object.defineProperty method
  3. When is the get function executed?

        (1) It will be executed once when the data is read for the first time (because it has a cache )

        (2) When the dependent data changes, it will be called again

      4. Advantages: Compared with the implementation of methods, there is an internal cache mechanism (multiplexing), which is more efficient and easier to debug

      5. Remarks:

           (1) Computed attributes will eventually appear on the vm, just read them directly

           (2) If the calculated attribute is to be modified, then the set function must be written to modify it accordingly, and the set will cause the data on which the calculation depends to change

2. Watch monitoring properties

  1. When the monitored property changes, the callback function hander is automatically called to perform related operations
  2. The monitored attribute must exist in order to be monitored! !
  3. Two Ways to Write Surveillance

        (1) Watch configuration passed in when new Vue

        (2) Monitoring via vm.$watch

2.1 Representation of watch monitoring

watch:{
  isHot:{
    immediate:true,
    //handler什么时候调用?即是isHot发生改变的时候
    handler(newValue,oldValue){
      //这里通常可以根据新旧值之间的变化而执行有些操作
      console.log('isHot被修改了,新值为:'+newvalue+'旧值为:'+oldvalue)
    }
  }
}

ps:

  1. Here the watch monitors the isHot attribute, you can try to change the value of isHot, you will find that the handler function in isHot will be triggered, and the console will output the corresponding prompt;
  2. isHot is an object with multiple configuration properties, where immediate means that isHot is called when it is initialized, and handler is triggered when isHot changes.

2.2 Watch depth monitoring

        Deep monitoring is to monitor the changes of the internal value of the object

  1. The watch in Vue does not detect changes in the internal value of the object by default (it can only monitor one layer)
  2. Configure deep:true to monitor the change of the internal value of the object (multi-layer data structure)

        Remarks: Vue itself can monitor the change of the internal value of the object, but the watch provided by Vue cannot by default

                 When using watch, decide whether to use deep monitoring according to the specific structure of the data

Note: The monitoring of watch is based on the existing attributes, pay attention to the following error demonstration

 Wrong way ①:


    data: {
      numbers: {
        a: 1,
        b: 2
      }
    }

    watch: {
     a: {
       handler(){
         console.log('a被改变了')
       }
      }
    }

 wrong way②

 Therefore, the correct way is to enable deep monitoring for this property

 It should also be noted that when using the shorthand method for property monitoring, only when the property does not need to configure other properties, such as deep monitoring or monitoring during initialization

2.3 Binding in the vue loop list: the role of key

        First of all, according to the introduction on the official website, it can be mainly used in Vue's virtual Dom algorithm to identify VNodes when comparing old and new nodes. When using a key, it rearranges the order of elements based on key changes, and removes elements whose key does not exist.

        Child elements with the same parent element must have unique keys, duplicate keys will cause rendering errors.

        When looping the list in vue, there are often two ways to bind: the value of the key. One is to use the index value index of the loop list as the key, but to use the unique identifier in the returned data as the key. No matter how the key is bound, the value of the key must be unique in the list. The reason why index can be used is that the index value must be unique. ,

        The following example illustrates the execution flow when binding a key with an index or a unique identifier

2.3.1 index as key

1. For example, the initial data is as follows:

   {id:'001',name:'张三',age:'18'},
    {id:'002',name:'李四',age:'19'},
    {id:'003',name:'王五',age:'20'}

2. Use v-for to loop through the data in the template. Display in the form of list li

      <ul>
            <li v-for="(index,item) in data" :key="index">
                {item.name} - {item.age}
                <input type="text">
            </li>
        </ul>

3. Then vue will generate virtual DOM according to the data, and the generated virtual DOM form is as follows:

        <li key="0">张三 - 18 <input type="text"></li>
        <li key="1">李四 - 19 <input type="text"></li>
        <li key="2">王五 - 20 <input type="text"></li>

4. Convert virtual DOM to real DOM

 ---------------------Split: The above is the process of vue converting from binding data and from virtual DOM to real DOM---------- ------------

5. Next, when the data is found to change, the data changes when the key binding value is index, and the changed data is as follows

             {id:'004',name:'老刘',age:'20'},
             {id:'001',name:'张三',age:'18'},
             {id:'002',name:'李四',age:'19'},
             {id:'003',name:'王五',age:'30'}

6. At this time, because the data has changed, vue will repeat the data rendering process. At this time, the virtual DOM generated according to the new data is as follows

            <li key="0">老刘 - 30 <input type="text"></li>
            <li key="1">张三 - 18 <input type="text"></li>
            <li key="2">李四 - 19 <input type="text"></li>
            <li key="3">王五 - 20 <input type="text"></li>

7. Convert virtual DOM to real DOM

 8. Next, explain why the above situation occurs?

        Due to the identification of the virtual DOM object when the key is in vue, when the data in the state changes, Vue will generate [new virtual DOM] according to [new data], and then Vue will perform [new virtual DON] and [old virtual DON] The difference comparison of , where the comparison rules are as follows:

         (1) The same key as the new virtual DOM is found in the old virtual DOM:

             - When the content in the old virtual DOM has not changed, use the previous real DOM directly (such as the input content above)

             - If the content in the virtual DOM changes, a new DOM will be generated directly, and then the previous real DOM in the page will be replaced

        (2) The same key as the new virtual DOM was not found in the old virtual DOM

               - Directly create new real DOM, then render to the page

        (3) Since the above example does not bind the key value, the key value is from top to bottom from 0-n every time the cycle is performed, and the top-to-bottom input value does not change, so it is directly reused

3 The principle of data binding in Vue

Let's take the same example to briefly explain the two-way data binding in vue

3.1 Example 1

For example, I want to directly click the button to directly access the data of an item in the century-old array persons: this.persons[0]={id:'001', name:'Mr. Ma', age:'50', sex:'Male '}

But found that the page is not up to date:

         Then we will find that it is invalid to directly change an item in the persons array, so according to the principle of Vue two-way data binding, how can we effectively change it?

The following are valid changes: (that is, to modify the specified properties of the array items)

        this.persons[0].name='马老师';
        this.persons[0].age=50;
        this.persons[0].sex="男"

3.2 Example 2

        When you want to add a new attribute to vue, you can't directly use this.student.sex=' male' to add it, so the newly added new attribute does not have two-way binding of data:

 

         So the question is, how to add new attributes to achieve responsiveness? According to the official website of vue, when you don’t define the data in data at the beginning, adding it directly is not responsive. If you want to add it directly in data, but add it somewhere later when you want to use it , can be implemented through the API, as follows:

                Vue.set(target,propertyName/index,value)

1. Parameters:

  • target :{Object |Array}
  • propertyName/index:{ staring | number }
  • value :{any}

2. Return value: the set value

3. Usage:

        Add a property to the responsive caprice and make sure that this new peopety is also responsive and triggers view updates. It must be used to add new properties on the corresponding object, because Vue cannot detect ordinary new properties (such as this.myObject.newProperty='hi')

Note: The object cannot be a Vue instance, or the root data object of a Vue instance

Example:

      methods: {
            addSex() {
                Vue.set(this.student, 'sex', '男')
            }
        }

3.3 Example 3

 

 3.4 Summary

  1. Vue will monitor data at all levels in data
  2. How to detect data in object?

             Realize monitoring through setter, and pass in the data to be detected when new Vue

             (1) The attribute added after the object. Vue does not do responsive processing by default

             (2) If you need to make the added attributes responsive, please use the following API:

                        Vue.set(target,propertyName/index,value) 或

                        vm.$set(arget,propertyName/index,value)

        3. How to check the data in the array?

                Realized by wrapping arrays and new elements, essentially doing two things: (Vue wraps related methods of manipulating arrays to achieve two-way data binding)

                 (1) Call the native corresponding method to update the array       

                 (2) Re-parse the template to update the page.

        4. To modify an element in the array in Vue, you must use the following method:

                  (1) Use this API: push(), pop(), shift(), unshift(), splice(), sort(), reverse(),

                  (2) Vue.set() or vm.$set()

        Special attention: Vue.set() and vm.$set() cannot add attributes to vm or vm's root data (vm._data) object

4. Collect form data

       4.1 Core Principles  

        The core is to add the value attribute to the form element through the v-model instruction

        Note that when using the v-model directive to implement two-way data binding, v-model essentially receives the value of the form element. Since the value entered by the user for the input box such as "input, textarea" is the value value, there is no need to bind the value value to the input. For other form elements that are not input boxes ( such as radio, checkbox, etc. ), if you want to use v-model to achieve two-way binding, you usually need to add a value attribute to it.

Examples are as follows:

 

 4.2 Summary

  1. <input type="text"/>, then the v-model collects the value value, and the user enters the value value
  2. <input type="radio"/>, then the v-model collects the value value, and the value value must be configured for the label
  3. <input type="checkbox"/>

        (1) If the value attribute of the input is not configured, then the collection is checked (checked or unchecked, it is a Boolean value)

         (2) Configure the value attribute of the input:

                - The initial value of v-model is non-number, then the collection is checked (checked or unchecked, it is a Boolean value)

                - The initial value of v-model is an array, so what is collected is an array of values

        4. Three modifiers of v-model

          (1) lazy: lose focus and collect data

           (2) number: the input string is converted into a valid number

           (3) trim: filter leading and trailing spaces

5 filters

6. Instructions 

6.1 v-html directive

  1. Function: Render the content containing the html structure like the specified node
  2. Difference from interpolation syntax

        (1) v-html will replace all the content in the node, { {xx}} will not

        (2) v-html can recognize html structure

      3. Serious attention: v-html has security issues! !

         (1) It is very dangerous to dynamically render arbitrary html on the website, and it is easy to attack by xss

         (2) Always use v-html on trusted content, never on user-submitted content! (For example, some malicious people will get your cookie through it, etc.)

6.2 v-cloak command

  1. The essence is a special attribute. After the Vue instance is created and takes over the container, the v-cloak attribute will be deleted
  2. Using css with v-cloak can solve the problem of showing {{xxx}} even when the network speed is slow

6.3 v-once instruction

  1. After the initial dynamic rendering of the node where v-once is located, it is regarded as static content (that is, it can only be read once)
  2. Future data changes will not cause the update of the v-once structure, which can be used to optimize performance

6.4 v-pre directive

  1.  Skip the compilation process of its node
  2. It can be used to skip: nodes that do not use instruction syntax and interpolation syntax will speed up compilation

 6.5 Custom Instructions

7 life cycle of vue

        Vue's life cycle is executed in the following order: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestory, destroyed.

7.1 beforeCreate

        Vue is initialized in the beforeCeate hook function, because the data monitoring and data proxy have not started yet, so the data in data and the methods in methods cannot be accessed through vm.

7.2 created

        At this point, data detection and data proxy have been completed, so the data in data and the method configured in methods can be accessed through vm here.

Note: After the warning is created, because Vue has not started compiling, it needs to go through the following beforeMount and mounted stages to complete the template parsing.

7.3 beforeMounted

        At this stage, vue has started to parse the template and generate virtual dom (in memory), and the page cannot display the parsed content yet. That is, what the page presents at this time is the DOM structure that has not been compiled by Vue . All operations on the DOM will not work in the end.

7.4 mounted

        After the above beforeMount, at this time vue has converted the virtual DOM in the memory into a real DOM and inserted it into the page.

  • What is presented on the page is the DOM compiled by Vue
  • All operations on DOM are valid (try to avoid operating DOM), so far the initialization process is over,
  • Generally run at this stage: start timers, send network requests, subscribe to messages, bind custom events and other initialization operations.

 7.5 beforeUpdate

        After the above periodic function, the page has been rendered, and the corresponding data can also be obtained.

        Here, if the data changes, the data is new here, but the page is old , that is to say, the page has not been updated synchronously with the data.

7.6 updated

        Here, based on the new data, a new virtual DOM is generated, and then compared with the old virtual DOM, and finally the page is updated, that is, the update of Model->View is completed. At this point, the data is new and so is the page . That is, keeping data and pages in sync.

Summary diagram

8 components

        Components are reusable Vue instances with a name.


        About VueComponents:

  1. The school component is essentially a constructor named VueComponent, which is not defined by the program, but generated by Vue.extend.
  2. We only need to write <school/> or <school><school/>, and Vue will help us create a school component instance object when parsing. That is, what Vue executes for us: new VueComponent(options).
  3. Special Note: Every time Vue.extend is called, a brand new VueComponent is returned! ! ( Vue will automatically execute new VueComponent(options) for us inside Vue )
  4. About this pointing:
    1. In component configuration:
      1. For data functions, functions in methods, functions in watch, and functions in computed, their this points to [VueComponent instance object]

              2. new Vue () configuration

                        1. Data functions, functions in methods, functions in watch, functions in computed, their this are all [Vue instance objects]

    5. The instance object of VueComponent can be referred to as vc (component instance object) for short

        Vue instance object, referred to as vm

       

8.1 Built-in objects

8.1.1 The prototype object is introduced first

function Demo(){
    this.a=1,
    this.b=2
}

//创建一个Demo的实例对象
const d = new Demo()

console.log(Demo.prototype)//显示原型属性
console.log(d.__proto__)//隐式原型属性

1. Each object (or constructor) has a prototype attribute prototype

2. Every instance of an object has an invisible prototype property

3. Both the prototype attribute of the constructor and the prototype attribute of the instance point to the prototype object

Demo.prototype === d.__proto__

4. The following verifies ` Demo.prototype === d.__ proto__`

//通过显示原型属性操作原型对象,追加一个x属性,值为99
Demo.prototype.x=99;
console.log('@',d.__proto__.x)
//或者直接输出d.x(因为找不到时也会往原型链上查找)
console.log(d.x)

8.1.2 Relationship between Vue and VueComponent

  1. An important built-in relationship: VueConponent.prototype.__proto__ === Vue.prototype
  2. Why this relationship: Let the component instance object vc access the methods and properties on the Vue prototype

Note: The invisible prototype attribute of the instance must point to the prototype object constructed by itself, so it is obvious

        The invisible attribute of Vue's instance object vm points to Vue's prototype object

        The prototype property of Vue's prototype object points to the prototype object of Object

 Thinking: So how are Vue and VueComponent connected?

Vue internally points the prototype object of VueConponent to the prototype object of Vue (purpose: so that both Vue instances and VueConponent instances can share Vue methods and instances)

1. 

 

         For example, I want to find the x attribute on vc. When there is no x attribute on vc, I will search along __proto__ (this proto points to the prototype object of VueComponent). When x is not found on the prototype object of VueComponent, I will go to proto Find x on the Internet. At this time, the prototype attribute proto of the prototype object of VueComponent in Vue (pointing to the Vue prototype object). At this time, find x on the Vue prototype object. This can be found. Note that if it is also in the prototype object of Vue If not found, continue to look for the proto of the Vue prototype object, that is, find the Object


 

9. Understanding of render function

        In the main.js file of the entry file, the Vue imported by default is not the full version, it is modified by the Vue developer on the basis of the full version of Vue (here called "incomplete" version), and the imported Vue does not have the ability to compile template function. Therefore, when you create a Vue instance in the main.js entry file and try to implement template compilation at the same time, as follows, an error will occur

The error is as follows:

Therefore, the vue team introduced the render function to implement template template compilation. The essential function of the render function is to generate nodes

//完整版的rander函数
render(createElement){
    return createElement('h1','你好啊') //render函数需要返回值
}

//简写
render:(q)=>{
    return q('h1','你好啊')
}

//精简简写
render: q=>q(App)//这里的App是import引入的App.vue组件


//
new Vue({
    el:'#app',
    //下面这行代码,完成了将App组件放入容器中
    render:h=>h(App)
})

Thinking : Since template compilation is to be performed, why didn't the vue team introduce a complete template compilation function directly at the beginning? The reason is that after your function is realized, your code needs to be packaged by webpack or other packaging tools, then after packaging, some vue files have been compiled into html, js, css that browsers can recognize And other files, then this compilation function is not needed online. To avoid extraneous actions and occupying memory, the vue team introduced vue without compilation function from the beginning.

Question: If the "incomplete" version of vue is introduced, how is the <template> tag in other components compiled?

Answer: A package is specially introduced in vue to parse the <template> tag in the component

Summary: About different versions of vue:

1. The difference between vue.js and vue.runtime.xxx.js:

        (1) vue.js is a complete version of Vue, including: core functions + template parser

        (2) vue.runtime.xxx.js is the running version of Vue, which only contains: core functions, no template parser

2. Because vue.runtime.xxx.js does not have a template parser, the template configuration item cannot be used, and the ceateElement function received by the render function needs to be used to specify the specific content.

9. Customize the function of the scaffolding

        1. Use vue inspect > output.js to view the default configuration of Vue scaffolding

        2. Create a new vue.config.js to customize the scaffolding. For details, see: Configuration Reference | Vue CLI

        3. Scaffolding file structure

 10. ref attribute

  1. Used to register reference information for elements or subcomponents (replacement of id)
  2. What the application gets on the html tag (such as div, h1, etc.) is the DOM element, and the application on the component tag (.vue) is the component instance object (vc)
  3. How to use

        Mark: <h1 ref="xxx">.....</h1> or <School ref="xxx"></School>

        Get: this.$refs.xxx

11. prop attribute

         The prop attribute plays an important role in realizing the communication between parent and child components.

The usage is as follows:

11.1 How to use

     In the parent component:   directly in the imported child component: <subcomponent variable name 1="value 1" variable name 2="value 2": variable name 3="value 3"/>

 In the subcomponent:

        Use the props attribute to receive the data passed by the parent component (the data received using props, similar to the data defined in data, is directly hung on the vm, so it can be used directly on the template, but it cannot be directly changed from the parent in props The component receives the received data, which can be changed indirectly, as will be discussed below)

 ps: When you want to change the data passed by the parent component, don't try to modify it directly. You can redefine a variable in data to receive the data, and then change it by changing the newly defined variable in data.

When the parent component passes data to the child component, you need to use the v-bind (abbreviation:) instruction to tell vue that the js expression is passed in instead of a string. When you don't use the v-bind command, then vue will default to the string type of the data you pass in.

11.2 Unidirectional data flow

  1. All props form a single downward binding between their parent and child props: parent rpop updates will flow down to child components, but not the other way around, which prevents accidental changes to the parent component's state from child components , making your app's data difficult to understand
  2. In addition, every time the parent component changes, all props in the child component will be refreshed to the latest value. This means that you should not change props inside a child component. If you do, Vue will be in the browser. A warning is issued in the console of the server.

       

11.3 Summary

        Function: Let the component receive data from the outside

(1) Transfer data:

        <Demo name="xxx"/>

(2) Receive data:

        The first way (receive only)

    props:['name']

        The second way (restricted type)

       props:{

               name:String
       }

        Third way (restrict type, restrict necessity, specify default value):

          props:{
                  name:{
                        type:String,//类型
                        required:ture,//必要性
                        default:'老王'//默认值
                  }
          }

 12.minix mixed in

        Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain options for arbitrary components. When a component uses a mixin, all of the mixin's options will be "mixed in" into the component's own options.

example:

1. Define a mixed object


2. Introduce a mixed object in the component

3. Summary

        Function: The common configuration of multiple components can be extracted into a mix-in object

        How to use:

                The first step is to define the mixin, for example:

{

    data(){......},

    methods:{...}
}

                The second step uses mixins, for example:

        (1) Global mix-in: Vue.mxiin(xxxx)

        (2) Local mixins: mixins: ['xxxx']

13. Plugins

        Plug-ins are usually used to add global functions to Vue. There are no strict restrictions on the functional scope of plug-ins --- generally there are the following types:

  1. Add a global method or property. Such as: vue-custom-element
  2. Add global resources: directives/filters/transitions etc. Such as vue-touch
  3. Add some component options via global mixins. Such as vue-router
  4. Add Vue instance methods by adding them to Vue.prototype .
  5. A library that provides its own API while providing one or more of the functions mentioned above, such as vue-router

13.1 Using plugins

        Use the global method Vue.use() to adapt the plugin, which needs to be done before you call new Vue() to start the application:

// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)

new Vue({
  // ...组件选项
})

 

 13.2 Summary

        Function: used to enhance Vue

        Essence: An object containing the install method, the first parameter of install is vue, and the second and subsequent parameters are the data passed by the plug-in user.

        Note: After introducing the plugin, remember to use Vue.use() to use the plugin (globally available)

14. Style

        In order to avoid conflicts between styles caused by duplication of class names between components, in Vue, the scope attribute is provided for the <style> tag. After adding scope, the styles between components do not affect each other. The principle of action is to add random attributes to the label every time it is rendered, so as to avoid style conflicts between components.

14.1. At the same time, other css compilers other than css are supported in vue, such as scss, less, etc. The attribute lang in <style> specifies the css processor you use.

14.2. Problem: How to solve the conflict with webpack when npm downloads the less package

 

 

 

 

15. Custom Events

1. A way of component communication, used in: child component ==> parent component

2. Usage scenario: A is the parent component, B is the word component, and B wants to pass data to A, then it needs to bind custom events to B in A (the callback of the event is in A, that is, to receive data there, just set the callback for the event there)

3. Bind custom events:

        ① The first way, in the parent component

<Demo @XXX="test"/> 或者 <Demo v-on:XXX="text"/>

        ⑤ The second way, in the component:

<Demo ref="demo"/>
......
mounted(){
    //这个this.test是定义在methods中的函数,可以避免this指向的问题
    this.$refs.xxx.$on('xxx',this.test)
}

        ③. If you want to customize the event only once, you can use the once modifier, or the $once method

4. Trigger a custom event: this.$emit('xxx', data)

5. Unbind the custom event: this.off('xxx')

6. Native DOM events can also be bound to components, and the .native modifier needs to be used

7. Note: When binding a custom event through this.$ref.xxx.$on('xxx', callback function), the callback must either be configured in methods or use an arrow function , otherwise there will be problems with this pointing!

16. Global Event Bus

1. A way of component communication, used for communication between any components

2. Install the global event bus:

new Vue({
    .....
    beforeCreate(){
        Vue.prototype.$bus=this
    }
})

3. Use the event bus:

        1. Accept data: If component A wants to receive data, then bind a custom event to $bus in component A, and the callback of the event stays in component A itself.

methods(){

    demo(data){
        ....
    }
}
mounted(){
    this.$bus.$on('xxx',this.demo)
}

        2. Provide data: this.$bus.$emit('xxx', data)

4. It is best to use $off in the beforeDestroy hook to unbind the events used by the current component

 17. Message Subscription and Publishing

17.1 Description

            The party that provides the data is the publisher

            What needs data is the subscription message party

17.2 Download related plug-ins

npm i pubsub-js

17.3 Use

  1.  Use import pubsub from 'pubsub-js' to introduce the plugin first
  2. On the subscribe message side :
mouuted(){
    pubsub.subscribe('hello',function(){
        console.log('有人发布了hello消息,这里hello消息的回调执行了')
    }
}

3. On the message publishing side

methods(){
    sendStudentName(){
        pubsub.publish('hello',666)
    }
}

 

4. Unsubscribe

 17.4 Summary

1. A way of component communication, used for communication between any components

2. Steps to use

        1. Install pubsub: npm i pubsub-js

        2. Introduction: import pubsub from 'pubsub-js'

        3. Accept data: A component wants to receive data, then subscribe to the message in A component, and the subscription callback stays in A component itself

methods(){
    demo(data){
        ....
    }
}
mounted(){
    this.pid=pubsub.subscribe('xxx',this.demo)//订阅消息

}

        4. Provide data: pubsub.publish('xxx', data)

        5. Unsubscribe, preferably in the beforeDestory hook, use PubSub.unsubscriber(pid) to unsubscribe

18. nextTick()

  1. Syntax: this.nextTick(callback function)
  2. Function: Execute the specified callback after the next DOM update
  3. When to use: When the data is changed and some operations are to be performed based on the updated DOM, it must be executed in the function specified by nextTick().
  4. scenes to be used:

                For example, in a unified event, when you just changed the data in the previous step and want to get the DOM in the next step, you immediately execute the next step at this time, then you may not get the wrong DOM, so it will affect the page effect. When you use this.nextTick () can be resolved.

19 Difference between HTML5 History mode and hash mode        

The intuitive difference between hash and history mode:

The default of vue-router is the hash mode. If you don’t want an ugly hash, we can use the history mode of the route. This mode makes full use of the history.pushState API to complete the URL jump without reloading the page

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

When you use the history mode, the URL is like a normal URL, such as http://yoursite.com/user/id, and it looks good too!

However, this mode also requires background support. Because our reference is a single-page client application, if there is no correct background configuration, when the user directly visits  http://oursite.com/user/id while browsing  , it will return 404.

So, you need to add a candidate resource on the server side that covers all situations: if the URL does not match any static resource, it should return the same  index.html page, which is the page your app depends on.

Guess you like

Origin blog.csdn.net/weixin_46872121/article/details/120241936