Create by jsliang on 2018-11-8 13:34:30

Recently revised in 2019-1-12 19:23:17

If you think this is a good article, please send me astar, yourstarIs my motivation to learn!Making the address


Jsliang has been refactoring the document library, so some of the links in this article may be broken, and Jsliang does not have the energy to maintain the old articles on the Nuggets side. Sorry about that. If you need to get the latest article, please click on the GitHub address above and go to the document library to view the adjusted article.


It is recommended to go through the table of contents and use the back to Table button for a better reading experience.

A directory

Do not toss the front end, and what is the difference between salt fish ~

directory
A directory
The second body
2.1 I met Vue
2.2 Mounting Data – Data
2.3 Further optimize EL
2.4 Interpolation – {{}}
2.5 Command -v -*
2.6 Events-methods
2.7 Template – Template
  2.7.1 Getting to know Components
  2.7.2 Communication between Parent and Child Components
  2.7.3 Sharing Components
2.8 Filter-filter
  2.8.1 Local filtering
  2.8.2 Global Filtering
2.9 Listening Data
  2.9.1 Listening Properties – Watch
  2.9.2 Computing Attributes – Computed
  2.9.3 Comparison between Watch, Computed and Methods
2.10 Passing DOM-slot
  2.10.1 Slot Single transfer
  2.10.2 named slot.
2.11 Vue Component Life cycle
  2.11.1 beforeCreate & created
  2.11.2 beforeMount & mounted
  2.11.3 beforeUpdate & updated
  2.11.4 beforeDestory & destory
  2.11.5 activated and deactivated
2.12 Obtaining DOM Elements
  2.12.1 Obtaining a DOM Element
  2.12.2 Obtaining component DOM Elements
  2.12.3 Vue. NextTick ()
Three practical
Four summarizes

The second body

Returns the directory

Think of the source when drinking water:Vue official document

Vue (pronounced vju/curliest, similar to View) is a set of progressive frameworks for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.

Learning version: V2.5.21 Preparation time: 2019-1-10

If the version change is too big or the article has not been updated for too long, please check the official Vue document to learn the latest Vue.

2.1 I met Vue

Returns the directory

So what does Vue do?

Without further ado, let’s go straight to the code implementation:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"</script> <script> new Vue({// 3. El - mount target, i.e.'#app'<div> template <div> template <div> template <div> template <div> template <div> ` <div> <p>Hello World</p> </div> ` }) </script> </body> </html>Copy the code

Now, let’s parse the code run:

  1. First, create a blank HTML template file that references Vue via CDN:

Vue generally comes in two versions: Development version: A friendly error message is displayed during development. Production version: a version used for online deployment with a small code package

Index.html code snippet

<! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script>
Copy the code
  1. Then, we write a mount point, our Vue, which DOM will eventually operate in:
<! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div>
Copy the code
  1. Finally, we do this by New a Vue instance object to our idappDOM node to operate:
New Vue({// 3. El - mount target, i.e. render at which mount point el: document.getelementById ('app'), // 4. Template - the content rendered to the mount point. <div> template: '<div> <p>Hello World</p> </div>'})Copy the code

Thus, we end up showing a simple reference to Vue, isn’t it pretty simple:

2.2 Mounting Data – Data

Returns the directory

If Vue is loaded only with the template template, it is not much different from jQuery. Here we use Vue data to render data:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"</script> <script> new Vue({// 3. El - mount target, i.e.'#app'<div> template <div> template <div> template <div> template <div> template <div> '<div> <p>{{text}}</p> </div>', // 5"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// The data to be used in template text:'Hello World! '
        }
      }
    })

  </script>
</body>

</html>
Copy the code

Here we can see that we have added a

tag to template and introduced a data called text in the form {{text}} :

<p>{{ text }}</p>
Copy the code

Next we define the contents of text in

to render the data:

data() {
  return{// The data to be used in template text:'Hello World! '}}Copy the code

In this way, we know that not only can we render the

tag from the template, we can also change the contents of the HTML by manipulating data or variables defined in JS.

2.3 Further optimize EL

Returns the directory

In Sections 2.1 and 2.2, we use EL in the following ways:

el: '#app'.Copy the code

The el mount, in the internal workings of Vue, looks up the values you pass in:

  • If the incoming is#appThen it judges the searchidappThe node;
  • If the incoming is.appThen it looks forclassappThe node;
  • If the node name is passed indivThen it looks for the node name…

We should be clear, such judgment search is to take time, more than one judgment is a sin.

So we can:

el: document.getElementById('app'),
Copy the code

This allows Vue to mount mount points directly to the ID for better load speed. So this is kind of a little optimization for EL.

2.4 Interpolation – {{}}

Returns the directory

If you remember, we used {{}} interpolation to manipulate data in data in Section 2.2.

Below, we further explain the interpolation expression {{}} can be what kind of SAO operation:

  • {{{name: ‘jack’}}}
  • String {{‘Hello World! ‘}}
  • Boolean: {{isTrue == -1}}
  • Ternary expressions: {{isTrue? ‘true’ : ‘false’}}

It’s not enough to read it literally. Let’s do it in code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> new Vue({// 3. El - mount target, i.e.'app'<div> template: '<div> <p>{{text}}</p> <p>{{{{name: <div> <p> <p>'jack'} }}</p>
          <p>{{ 'Hello World! ' }}</p>
          <p>{{ isTrue == -1 }}</p>
          <p>{{ isTrue ? 'true' : 'false'}}</p> </div> ', // 5"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// The data to be used in template text:'Hello World! ',
          isTrue: true
        }
      }
    })

  </script>
</body>

</html>
Copy the code

It appears in the browser as:

Key code explanation:

<div> <! <p>{{text}}</p> <! --> <p>{{{name:'jack'} }}</p> <! -- Assign string directly to tag --> <p>{{'Hello World! '}}</p> <! IsTrue is set to Boolean in datatrueAnd -1 turns into a Boolean value of 0false, so they are not equal. The output value isfalse--> <p>{{ isTrue == -1 }}</p> <! -- Run the ternary expression, isTrue istrue<p>{{isTrue?'true' : 'false' }}</p>
</div>
Copy the code

Through the use of ternary expressions, we can do some judgment: the last element of the array, whether dynamic display hide, etc.

2.5 Command -v -*

Returns the directory

In Vue, interpolation expressions like {{}} alone cannot satisfy our desire to manipulate data. Therefore, Vue provides some more convenient operations for page + data in the form of V-if, V-bind, etc. : instructions

  • v-text
  • v-html
  • v-if
  • v-else-if
  • v-else
  • v-show
  • v-bind
  • v-on
  • v-model
  • v-for

Here, a page is used to display all instructions. If you want to know the instructions one by one, you are recommended to go to the official website to check and learn: Vue instructions

So, how do the above instructions work? Here’s an index. HTML and a diagram to show the basic usage:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"< span style> /* color: red; color: red; color: red; } .color-blue { color: blue; } .color-green { color: green; } </style> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> new Vue({// 3. El - mount target, i.e.'app'<div> template: '<div> <p>v-text demo </p> <p v-text='vTextOrHtml'></p> <br/> <p> V-HTML demo </p> <p V-HTML ='vTextOrHtml'> < / p > < br / > < p > v - if - > v - else - if - > v - else demo < / p > < p v - if ='vIf == 1'>Hello v-If</p>
          <p v-else-if='vIf == 2'> Hello v - else - if < / p > < p v - else > Hello v - else < / p > < br / > < p > v - show demo < / p > < p v - show ='isTrue'> < / p > < br / > < p > v - bind: * * * * * * - > : demo < / p > < input v - bind: value ="vBind" v-bind:class="colorRed" type="text"/>
          <input v-bind:other1="other1" :other2="other2" :other3=" 'other3' " value="Hello: Property value" type="text"/ > < br / > < br / > < p > v - on: click - > @ click demo < / p > < button v - on: click =" vBind= 'Hello v-on:click' "</button>< button@click ="changevBindValue"</button><br> <p> <input V-model ="vModel" type="text"/ > < p > {{vModel}} < / p > < br / > < p > v - for demo < / p > < ul v - for ="(item, index) in vFor" :class="item.classStyle"> < li > {{index + 1}}, {{item. The name}} - {{item. Age}} < / li > < / ul > < / div > `, / / 5. Data - data, Var text = var text = var text = var text = var text = var text = var text = var text ="Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// The data to be used in the template // v-text and v-html use the data vTextOrHtml:< p style="color: red">, // v-if to use data vIf: 2, // v-show to use data isTrue:false// vBind uses data vBind:"Hello v-bind", // v-bind to dynamically bind class to change style colorRed:'color-red'// Use the form of the v-bind: attribute other1:'other1', // same as other2:'other2'// vModel uses data vModel:'Hello v-model', // vFor: [{name:'Joe', // Name: 22, // age classStyle:"color-red"// style}, {name:'bill',
              age: 23,
              classStyle: "color-blue"
            },
            {
              name: 'Cathy',
              age: 24,
              classStyle: "color-green"
            }
          ]
          
        }
      }
    })

  </script>
</body>

</html>
Copy the code

Let’s take a look at the page:

Here, we take a look at the code:

<div> <! <p vTextOrHtml = <p vTextOrHtml ='vTextOrHtml'></p> <br/> <! <p vTextOrHtml = <p vTextOrHtml ='vTextOrHtml'></p> <br/> <! -- v-if/v-else -- if/v-else -- if/v-else -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if -- if If there are more cases in the project, add v-else-if --> <p v-if='vIf == 1'>Hello v-If</p>
  <p v-else-if='vIf == 2'>Hello v-else-if</p> <p v-else>Hello v-else</p> <br/> <! -- 4. V-show determines whether isTrue isTrue or false. It differs from v-if in that v-if is false does not render v-show in Element'isTrue'></p> <br/> <! V-bind :value - write v-bind:value - write v-bind:value - write v-bind:class v-bind:other1="other1"<input other1="other1" />>
   -->
  <input v-bind:value="vBind" v-bind:class="colorRed" type="text"/>
  <input v-bind:other1="other1" :other2="other2" :other3=" 'other3' " value="Hello: Property value" type="text"/><br/> <br/> <! <button V-on :click= <button v-on:click= <button v-on:click= <button v-on:click=" vBind= 'Hello v-on:click' "</button>< button@click ="changevBindValue"</button><br> <br/> <! V-model is a two-way data binding, where changes to the input above affect the content shown below --> <input v-model="vModel" type="text"/> <p>{{ vModel }}</p> <br/> <! -- 8. V-for v-for loop body traversal output --> <ul v-for="(item, index) in vFor" :class="item.classStyle">
    <li>{{index+1}}. {{item.name}} - {{item.age}}</li>
  </ul>
</div>
Copy the code

The difference between V-bind and V-model:

  • V-bind: Syncs data from the Vue to the page, meaning most of this value is used by the front end to pass fixed data to the browser. V-bind can assign a value to any attribute, a one-way data stream from Vue to the page, Vue -> HTML.
  • V-model: Two-way data binding. The front end sends data to the browser. The front end is aware of changes made by the user to the browser. The V-model can only bind bidirectional data to elements that have value attributes (it must use elements that have value attributes), namely Vue -> HTML -> Vue

As for the Vue directive, here WE have a brief overview of it and know how it is used. If you want to learn in detail, remember to go to the official document: Vue document

2.6 Events-methods

Returns the directory

In chapter 2.5, we bound event methods to a button by using V-on :click in it.

However, in 2.5, we covered the use of the event method in general, but we only got a glimpse of it.

Here, we extract them for explanation:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> new Vue({// 3. El - mount target, i.e.'app'<div> template: '< button@click ="addStyle"</button> ', // 5. Data - data - var text ="Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// Function methods () {// Function methods () {// Function methods (); { addStyle(e) { e.toElement.style.background ="red"
        }
      }
    })

  </script>
</body>

</html>
Copy the code

The click effect of the page is as follows:

Now let’s analyze the page:

  1. First of all,On the top<button>Medium, we pass@clickBind eventsaddStyle:
<button @click="addStyle"> Add inline styles </button>Copy the code
  1. Then,, method writing, need to write anddataAt the same level ofmethodsIn:
Methods: {// method addStyle:function(e) {
    e.toElement.style.background = "red"}}Copy the code
  1. then, we pass parameterse, you can get the element when clicked. Through searching, we find that the directory structure of its style is as follows:
- button
  - toElement
    - style
      - background
Copy the code
  1. Finally, we changed the background of the button directly when the user clicked it.

2.7 Component-Components

Returns the directory

On the blackboard! On the blackboard! On the blackboard!

Component is the focus of Vue learning, component-based SPA or SSR page production, so that we can develop more easily.

2.7.1 Initial Components

Returns the directory

In the previous sections, we’ve been writing HTML tags using the template: form. However, as the project grows, it becomes more complicated to modify if all the code is in a template. Therefore, we should find a way to divide it, such as a page into header, content, and footer. So when we need to change the nav, we just change it in the header.

Page structure

- app
 - header
 - content
 - footer
Copy the code

This idea is embodied in Vue as components (parts that come together). So, in Vue, how to do, in order to better achieve the division of components?

First, let’s stroke the logic:

In the previous section, in the definition of Vue, we mounted the first template to the node with the id app. Template is then divided into three blocks: Header, Content, and footer.

Here, we call the #app template parent, header, and so on child, as if the father had three sons below him.

Then, we try to pull the individual components out of new Vue:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> // declare the entry component var App = {template: '<h1> I am the entry component </h1>'} new Vue({// 3. document.getElementById('app'), // 4. Template - the content rendered to the mount point // the outermost layer must be wrapped, such as <div> template:'<app/>', // 5. Data - The data needed in the operation // can be understood as var text = in jQuery"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// Function methods () {// Function methods () {// Function methods (); App: app}}) </script> </body> </ HTML > </script> </body> </ HTML >Copy the code

The page looks like this:

Next, let’s analyze the trilogy going on:

  1. incomponentIs defined and extracted fromApp
  2. innew VueOutside the definitionApp
  3. intemplateThe use ofApp

So, we’ve separated the individual components, and new Vue is the parent of App, and App is the child of New Vue.

Finally, since we did the single component extraction above, we now implement the multiple component extraction:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learns </title> </head> <body> <div id="app"></div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"Var MyHeader = {template: '<div> I am the header </div>'}; Var MyContent = {template: '<div> I am body </div>'}; Var myFooter = {template: '<div> I am bottom </div>'} new Vue({el: document.getelementById ({el: document.getelementById))'app'), components: {// Declare the components to be used // Key is the component name, value is the component object'my-header': MyHeader,
        'my-content': MyContent,
        'my-footer': myFooter
      },
      template: `
        <div>
          <my-header/>
          <my-content/>
          <my-footer/>
        </div>
      `
    })
  </script>
</body>

</html>
Copy the code

In this way, we have done the component extraction.

Note:templateThere is only one root node. If there is no root node, Vue will give you an error.

  template: `
    <my-header/>
    <my-content/>
    <my-footer/>
  `
Copy the code

That’s the wrong way to write it, remember that.

MyHeader, myContent and myFooter can be used to write data and methods as new Vue

Such as:

var MyHeader = {
  data() {
    return{/ /... Define the data}} template: ` < h1 > < / h1 > I am the head `, the methods: {/ / define methods}};Copy the code

2.7.2 Communication between Parent and Child Components

Returns the directory

Now that we’ve divided parent components in the previous section, here’s something more interesting: parent component communication.

Between components, our new Vue is the parent (parent component), which has its own data. Then, the child component will also have its own data.

  • Suppose one day, a father finds his son and wants to tell him:"In fact, you are not my biological, your name is ***".

So, what can we do in Vue to let its children know what its last name is? Let’s look at the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> // subcomponent var Son = {template: '<div> MY name: {{name}}</div>', props: ['name'} new Vue({// 3. El - mount target el: document.getelementById ('app'<div> template: '<son :name=', // 4"name"></son> ', // 5"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// the name of the data to be used in template:'Leathery shrimp'}}, // 6. Function methods: {}, // 7. Son: son}}) </script> </body> </ HTML >Copy the code

After writing the code, we can see it in the browser. The browser displays: My name: Mantis Shrimp.

Oh, the father’s son was named PI. At the same time, we know that the data in the parent sends the data in the parent to the child by v-bind:***. The child component, on the other hand, gets the parent data through the props definition.

So we have the parent component passing data to the child component.

2.7.3 Sharing Components

Returns the directory

In the above, we mentioned:

- App
 - my-header
 - my-content
 - my-footer
Copy the code

On the App component, we have mounted three subcomponents: myHeader, myContent, and myFooter.

  • But if, one day, a girl (common component) appears and the girl’s name is:beautifulGirl. Then not only the three sons (the child component) tried to woo her, but the father (the father component) also (crazy).

In what way can both father and son have access to the girl in Vue? (How can parent and child components both use common components?)

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"Var MyHeader = {template: '<div> I am the header, I want to know </beautiful-girl></ beautiful-girl></div>'}; Var MyContent = {template: '<div> </beautiful-girl></ beautiful-girl></div>'}; Var myFooter = {template: '<div> I am at the bottom, I want to know < beauty-girl ></ beauty-girl ></div>'} // declare common component Vue.component('beautiful-girl', {template: '<span> -- beautiful girl -- </span>'}) new Vue({// 3.'app'), // 4. Template - the content rendered to the mount point // the outermost layer must be wrapped, such as <div> template: '<div> <my-header/> <my-content/> <my-footer/> </div>', // 5"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// Function methods () {// Function methods () {// Function methods (); {}, // 7. Components - Component name Components: {// key is component name, value is component object'my-header': MyHeader,
        'my-content': MyContent,
        'my-footer': myFooter,
      }
    })

  </script>
</body>

</html>
Copy the code

Vue.component(‘ component name ‘,{}) is used to register a global component named beautiful-girl, so that both parent and child components can call this component directly and display it in the browser as:

Now both fathers and sons can communicate with beautiful girls. Did the father find his son a stepmother, or did the son find his love? Stay tuned for…

2.8 Filter-filter

Returns the directory

In our work, we often need to filter some data returned from the back end. For example: our Java brother returned money, is the decimal system, that is: 1 yuan = 100 points. So I return 2000, which is actually 20 dollars. So how do we filter data in Vue?

2.8.1 Local filtering

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"Var MyHeader = {template: '<div> I am the header, I want to know </beautiful-girl></ beautiful-girl></div>'}; Var MyContent = {template: '<div> </beautiful-girl></ beautiful-girl></div>'}; Var myFooter = {template: '<div> I am at the bottom, I want to know < beauty-girl ></ beauty-girl ></div>'} // declare common component Vue.component('beautiful-girl', {template: '<span> -- beautiful girl -- </span>'}) new Vue({// 3.'app'), // 4. Template - the content rendered to the mount point // the outermost layer must be wrapped, such as <div> template: '<p> I am more money, I have {{money}} a little more: ${{money | addDot}}, mixed with me have ambition ~ < / p > `, / / 5. Data - data that is needed in the operating data can be understood as / / var text = in jQuery"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return {
          // template 中要使用的数据
          money: 1000000
        }
      },
      // 6. methods - 方法,即我们的页面事件
      // 可以理解为在 jQuery 中定义 Function
      methods: {
        
      },
      // 7. components - 组件名称
      components: {
        // key 是组件名,value 是组件对象

      },
      // 8. filters - 组件内的过滤器
      filters: {
        addDot(money) {
          return (money / 1000000 + "000000");
        }
      }
    })

  </script>
</body>

</html>
Copy the code

Above, we filter the data using the addDot method in filters to change the value of money from 10000000 to 1.000000.

2.8.2 Global Filtering

Returns the directory

Then, after trying the benefits of local filters, we can also try the global filter notation:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"</script> <script> // global filter vue.filter ('addDot'.function(money) {
      return (money / 1000000 + "000000"); }) new Vue({// 3. El - mount target, i.e. render at which mount point el: document.getelementById ('app'), // 4. Template - the content rendered to the mount point // the outermost layer must be wrapped, such as <div> template: '<p> I am more money, I have {{money}} a little more: ${{money | addDot}}, mixed with me have ambition ~ < / p > `, / / 5. Data - data that is needed in the operating data can be understood as / / var text = in jQuery"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// we can use the data in the template: money: 1000000}}, // 6. {}, // 7. Components - Component name Components: {// key is the component name, value is the component object}, // 8. Filters - Filters within the component: { } }) </script> </body> </html>Copy the code

Finally, the page displays as:

2.9 Listening Data

Returns the directory

In Vue, we have two-way data binding via v-Model, that is, values entered in of the page can be retrieved in our Vue; Data defined in the Vue is also rendered instantly to the page.

But, in code, how do we get the data it’s entering in real time?

2.9.1 Listening Properties – Watch

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> new Vue({// 3. El - mount target, i.e.'app'<div> template: '<div> <inputtype="text" v-model="money"/> <span>{{money}}</span> </div> ', // 5"Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// the data to be used in template is money:' '}}, // 6. Function methods: {}, // 7. Filters - filters within the component: {}, // 9. Watch - listen property watch: {// key: {// key: { Money (newVal, oldVal) {console.log(newVal, oldVal); } } }) </script> </body> </html>Copy the code

Thus, when we enter 11 ones, the browser’s Console output reads:

2.9.2 Computing Attributes – Computed

Returns the directory

Above, we talked about using watch to monitor the change of number, string and other fields in data. However, in Vue, for the convenience of our monitoring operations, Vue also defines a method: computed, through which we can monitor all the data defined in data.

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learns </title> </head> <body> <div id="app"></div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>

    new Vue({
      el: document.getElementById('app'),
      template: `
        <div>
          <input type="text" v-model="number1" />
          +
          <input type="text" v-model="number2" />
          *
          <input type="text" v-model="number3" />
          =
          {{result}}
        </div>
      `,
      data: {
        number1: 0,
        number2: 0,
        number3: 0,
        result: ' '}, computed: {// If the original value does not change, cache function optimization mechanism result:function() {// Monitor object, write inside function, // any function inside this. The current function is triggered by changes to related propertieslet addSum = parseInt(this.number1) + parseInt(this.number2);
          let allSum = addSum * this.number3;
          return allSum;
        }
      }
    })

  </script>
</body>

</html>
Copy the code

The result is shown in the GIF below:

2.9.3 Comparison between Watch, Computed and Methods

Returns the directory

We’ve covered two things above: watch and computed.

So it’s metaphysical time again, dealing with monitored data. When do we use Vue, when do we use Watch, and when do we use computed? Then, if we are adding methods, when do we use them again?

First, let’s compare computed and methods:

  • computedIs based ondataData changes while the operation is performed. namelyThis. Arbitrary dataChange, then,computedWill change; And if theThis. Task dataConstant, thencomputedIt executes its cache policy and does not update
  • methodsUsually triggered by something like a click, such as a user passing@ click = "method"To change the data.

Then, we compare computed with watch:

If the computed method in the preceding section is replaced with watch:

Index.html code snippet

Result (newVal, oldVal) {console.log(newVal, oldVal); this.result = this.number1 + this.number2 * this.number3; }},Copy the code

You can see that the result data does not change, because it is specific to computed. If you need to replace the computed method in the section above with watch, then you need:

Index.html code snippet

// 9. Watch - listen property watch: {// key: Data attribute attribute name number1(val) {this.result = parseInt(this.number1) + parseInt(this.number2) * parseInt(this.number3); }, number2(val) { this.result = parseInt(this.number1) + parseInt(this.number2) * parseInt(this.number3); }, number3(val) { this.result = parseInt(this.number1) + parseInt(this.number2) * parseInt(this.number3); }},Copy the code

Thus, you should know that if watch needs to perform computed functions, it needs to listen for every attribute that needs to be changed.

Finally, here’s a rough description of the difference between Watch and computed:

  • computedEmphasize calculation, for examplec = a + b.bIt’s constantly changing from the outside, because you just showc, so usecomputed. whilewatchAttribute emphasizes its own value changes before and after the action, if needed to completec = a + b“Then you need towatchdataabChanges are executed in the method when the two changec = a + b.
  • watchHas an advantage in handling asynchronous or expensive operations.
    • Performing asynchronous operations cannot return results serially, usingwatch;
    • For expensive operations to avoid blocking the main thread, usewatch;
    • Simple and serial return, usecomputed.
  • computedIt is dependent on the value of the binding. If the value of each operation does not change, the calculation is not performed. It has the caching feature. Watch will listen for the changing state and execute the defined function body regardless of whether the value of the operation changes, hence data(newVal, oldVal).

If you’re serious, check out the official documentation: Compute Properties and Listeners

2.10 Passing DOM-slot

Returns the directory

In our daily work, some common functions, such as: sidebar, top navigation bar, etc., will be commonly encapsulated, and when we want to use them, we can directly reference them. So what else do we need to know in Vue to implement this kind of functionality?

2.10.1 Slot Single transfer

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var myLi = {
      template: `
        <li><slot></slot></li>
      `
    };

    Vue.component('my-li', myLi); var App = { template: ` < div > < ul > < my - li > < button > I am the first row button button < / button > < / my - li > < my - li > < h3 > I am the second line of h3 tag < / h3 > < / my - li > < my - li > < a href ="javascript:void(0)"> I'm in the third row a navigation < / a > < / my - li > < my - li > < span > I am in the fourth row span tag < / span > < / my - li > < / ul > < / div > `}; New Vue({// 3. El - mount target, i.e. render at which mount point el: document.getelementById ('app'), // 4. Template - the content rendered to the mount point // the outermost layer must be wrapped, such as <div> template: '<app/>', // 5. data - data, i.e. data needed in the operation // can be understood as in jQuery var text ="Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// Function methods () {// Function methods () {// Function methods (); {}, // 7. Components - Component name Components: {// key is the component name, value is the component object app: app}, // 8. Filters - Filters within the component: {}, // 9. Watch - listen property watch: {// key: data property name}, // 10. Computed - Computed property computed: {// If the original value is unchanged, computed performs caching, that is, does not call a method}}) </script> </body> </ HTML >Copy the code

The result is shown below:

So, in the code above, what did we do?

First, as shown in the code and its resulting diagram, we have a component App mounted in our new Vue.

new Vue({
  el: document.getElementById('app'),
  components: {
    app: App
  },
  template: `
    <app/>
  `
})
Copy the code

The purpose of the App, then, is to dynamically reference a LI component

var App = {
  template: `
    <div>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
      </ul>
    </div>
  `
};
Copy the code

Next, while defining the myLi component globally, we enable it to dynamically load dom nodes through the
slot.

var myLi = {
  template: `
    <li><slot></slot></li>
  `
};

Vue.component('my-li', myLi);
Copy the code

Finally, in the App, we pass it different DOM nodes to dynamically generate the App.

var App = { template: ` < div > < ul > < my - li > < button > I am the first row button button < / button > < / my - li > < my - li > < h3 > I am the second line of h3 tag < / h3 > < / my - li > < my - li > < a href ="javascript:void(0)"> I'm in the third row a navigation < / a > < / my - li > < my - li > < span > I am in the fourth row span tag < / span > < / my - li > < / ul > < / div > `};Copy the code

This gives us a clear idea of how to dynamically load DOM nodes through
, which helps us better in Vue development.

2.10.2 named slot.

Returns the directory

In the previous section, we talked about the use of a single slot. But what if the component wants to hold the number of slots depending on whether the parent passes a variable?

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var mySlot = {
      template: `
        <ul>
          <li>
            <slot></slot>
          </li>
          <li>
            <slot name="one"></slot>
          </li>
          <li>
            <slot name="two"></slot>
          </li>
          <li>
            <slot name="three"></slot>
          </li>
        </ul>
      `
    };

    Vue.component('my-slot', mySlot); var App = { template: ` <div> <my-slot> <p>Helo World! </p> <button slot="one"> button </button> <a href="javascript:void(0)" slot="two"> Link </a> </my-slot> </div> '}; New Vue({// 3. El - mount target, i.e. render at which mount point el: document.getelementById ('app'), // 4. Template - the content rendered to the mount point // the outermost layer must be wrapped, such as <div> template: '<app/>', // 5. data - data, i.e. data needed in the operation // can be understood as in jQuery var text ="Hello World!"// {{text}} is one of the ways to render data to DOMdata() {
        return{// Function methods () {// Function methods () {// Function methods (); {}, // 7. Components - Component name Components: {// key is the component name, value is the component object app: app}, // 8. Filters - Filters within the component: {}, // 9. Watch - listen property watch: {// key: data property name}, // 10. Computed - Computed property computed: {// If the original value is unchanged, computed performs caching, that is, does not call a method}}) </script> </body> </ HTML >Copy the code

The renderings are as follows:

Let’s look at what we did in the code:

First, we can see from the following code that the slot of the first Li is an unnamed default slot, so it displays data as P in the page.

var mySlot = { template: ` <ul> <li> <slot></slot> </li> </ul> ` }; var App = { template: ` <div> <my-slot> <p>Helo World! </p> <button slot="one"> button </button> <a href="javascript:void(0)" slot="two"> Link </a> </my-slot> </div> '};Copy the code

and link This indicates that it specifies code receipt that requires
in the component. So the second and third lines show buttons and links.

Finally, since
in the last li, the name=”three” is not used in the App component, so it is null.

2.11 Vue Component Life cycle

Returns the directory

In Vue, there are hooks for when to render the virtual DOM to the DOM, or when to destroy code:


  • beforeCreate
  • created

  • beforeMount
  • mounted

  • beforeUpdate
  • updated

  • activated
  • deactivated

  • beforeDestory
  • destory

The Vue official documentation has diagrams and documentation for the lifecycle: Official documentation – Vue Lifecycle

The following code demonstrates the use of these five life cycles.

2.11.1 beforeCreate & created

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> var lifeCycle = {template: '<div> I am the lifeCycle component </div>, data:function() {
        return {
          text: 'Hello World! '
        }
      },
      beforeCreate: function() {console.log(this.text); // [Console] undefined }, created:function() {console.log(this.text) after the component is created; // [Console] Hello World! } /* * If lifeCycle is used, this will trigger the above event functions (hook functions) * created can manipulate data and can implement Vue -> page effects * application: } var App = {components: {'life-cycle': lifeCycle
      },
      template: `
        <div>
          <life-cycle></life-cycle>
        </div>
      `
    }

    new Vue({
      el: document.getElementById('app'),
      components: {
        app: App
      },
      template: `
        <app/>
      `
    })
    
  </script>
</body>

</html>
Copy the code

As you can see in the code, lifeCycle is referenced in our App.

Created (created after the component is created) and created (created after the component is created). For data, the two hook functions for the new TAB are beforeCreate and created (for the new TAB). Undefined, and the other occurs after data is mounted, so it prints: Hello World! .

2.11.2 beforeMount & mounted

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> var lifeCycle = {template: '<div> I am the lifeCycle component </div>, data:function() {
        return {
          text: 'Hello World! '
        }
      },
      beforeMount: function() {console.log(document.body.innerhtml) before Vue takes effect; }, mounted:function() {// Vue works and loads data into the DOM after console.log(document.body.innerhtml); } } var App = { components: {'life-cycle': lifeCycle
      },
      template: `
        <div>
          <life-cycle></life-cycle>
        </div>
      `
    }

    new Vue({
      el: document.getElementById('app'),
      components: {
        app: App
      },
      template: `
        <app/>
      `
    })

  </script>
</body>

</html>
Copy the code

So, although they work, one is before Vue works, and one is after Vue loads data into the DOM.

How can we observe it in action?

BeforeMount is the hook function BEFORE I load it. Mounted is the hook function after I load it. It is the DOM after Vue.

2.11.3 beforeUpdate & updated

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var lifeCycle = {
      template: `
        <div id="update"> <p> I am a lifecycle component </p> <p>{{text}}</p> < button@click ="text = '! dlroW olleH'"</div> ', data:function() {
        return {
          text: 'Hello World! '}}, // Based on data changes affecting the page beforeUpdate:function() {// change console.log(document.getelementById ()'update').innerHTML);
      },
      updated: function() {// change console.log(document.getelementById ()'update').innerHTML); } var App = {components: {} var App = {components: {} var App = {components: {}'life-cycle': lifeCycle
      },
      template: `
        <div>
          <life-cycle></life-cycle>
        </div>
      `
    }

    new Vue({
      el: document.getElementById('app'),
      components: {
        app: App
      },
      template: `
        <app/>
      `
    })

  </script>
</body>

</html>
Copy the code

Before parsing the code, let’s look at its output:

As you can see, beforeUpdate fetches the original DOM and updated fetches the new DOM.

They are realized in the above code as: get the DOM changes before and after the

  • Summary:beforeMount & mounted) VS (beforeUpdate & updated

The beforeMount and beforeUpdate groups both monitor DOM changes. What’s the difference?

The answer is that we use beforeMount and Mounted if we need to monitor DOM changes as the page loads. However, if we want to monitor user actions (click events, etc.), we need to use beforeUpdate and updated, because unlike beforeMount and Mounted, which are executed once early in the page mount, they can be executed multiple times based on user actions.

2.11.4 beforeDestory & destory

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var lifeCycle = {
      template: `
        <div id="update"> <p> I am the lifecycle component </p> </div> ', // corresponding parent component V-if ==falseThis generates the following hook function that destroys the current component beforeDestroy:function() {// Before destroying console.log()'before instance destruction. At this step, the instance is still fully available. ');
      },
      destroyed: function() {// After destroying console.log()'called after the Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. ');
      }
    }

    var App = {
      components: {
        'life-cycle': lifeCycle
      },
      data: function() {
        return {
          isExist: true
        }
      },
      template: `
        <div>
          <life-cycle v-if="isExist"></life-cycle>
          <button @click="isExist = ! isExist"</button> </div> '} new Vue({el: document.getelementById ({el: document.getelementById))'app'),
      components: {
        app: App
      },
      template: `
        <app/>
      `
    })

  </script>
</body>

</html>
Copy the code

In this case, when we click

As you can see, when we click

If isExist changes to true, the beforeCreate and created hook functions will be triggered. If isExist changes to true, the beforeCreate and created hook functions will be triggered.

2.11.5 activated and deactivated

Returns the directory

After a long time of work, we know that if we frequently manipulate the DOM, we will affect the performance of the hook functions beforeCreate and created and beforeDestory and destory. How do we prevent some part of our code from manipulating the DOM too often and listening for it?

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var lifeCycle = {
      template: `
        <div id="update"> <p> I am a lifecycle component </p> </div> ', activated:function() {
        console.log("Component is activated");
      },
      deactivated: function() {
        console.log("Component is disabled");
      }
    }

    var App = {
      components: {
        'life-cycle': lifeCycle
      },
      data: function() {
        return {
          isExist: true
        }
      },
      template: `
        <div>
          <keep-alive>
            <life-cycle v-if="isExist"></life-cycle>
          </keep-alive>
          <button @click="isExist = ! isExist"</button> </div> '} new Vue({el: document.getelementById ({el: document.getelementById))'app'),
      components: {
        app: App
      },
      template: `
        <app/>
      `
    })

  </script>
</body>

</html>
Copy the code

In the code, we wrap our child components with
, the built-in component of Vue.

The activated and deactivated hook functions are then activated when we enter the page and click the button:

As you can see, when we enter the page, it tells us that the component is active. When we first click the

  • Summary: At this point, I hope you go back to the beginning of the chapter on the life cycle and read the official life cycle diagram, which will help us understand the declaration cycle better. If it’s still not clear enough, click the button next to the image to go to the official documentation for an official breakdown of the life cycle. [Back to deeper Learning]

2.12 Obtaining DOM Elements

Returns the directory

In your daily development, you might think of manipulating DOM elements. $(“#id”); $(“#id”); $(“#id”);

2.12.1 Obtaining a DOM Element

Returns the directory

Without further ado, first the code:

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var App = {
      template: `
        <div>
          <button ref="btn"> button </button> </div> ', beforeCreate:function() {// We can't manipulate data here, just initialize events... console.log(this.$refs.btn); // [Console] undefined
      },
      created: functionConsole. log(this) {console.log(this);$refs.btn); // [Console] undefined
      },
      beforeMount: function() {// new Vue is loaded, replace <div id="app"> < / div > before the console. The log (this.$refs.btn); // [Console] undefined
      },
      mounted: function() {// After loading data console.log(this).$refs.btn.innerHTML); // [Console] button}} new Vue({el: document.getelementById ('app'),
      components: {
        app: App
      },
      template: `<app/>`
    })

  </script>
</body>

</html>
Copy the code

Let’s take a look at the page:

First, we write ref = “BTN” in the COMPONENT’s DOM section (

$refs.btn (mounted) {this.$refs.btn () {this.$refs.btn ()

This will show you how easy it is to get DOM elements via Vue in some scenarios.

2.12.2 Obtaining component DOM Elements

Returns the directory

Above, we retrieved parts of a single DOM node. What if we needed to retrieve the entire child component?

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script> var tempComponent = {template: '<div> I am a temporary component </div>'} Vue.component('temp', tempComponent);

    var App = {
      template: `
        <div>
          <temp ref="temp" />
        </div>
      `,
      mounted: function() {// After loading data console.log(this).$refs.temp.$el);
      }
    }

    new Vue({
      el: document.getElementById('app'),
      components: {
        app: App
      },
      template: `<app/>`
    })

  </script>
</body>

</html>
Copy the code

So before we analyze it, let’s see what the console prints;

You can see here that it prints out a bunch of stuff about the component, where

  • $children– Children of the current component
  • $el– Element node of the current component
  • $parent– The parent of the current component
  • $root– access tonew VueThe instance

Then we find that the element $el is the content of the DOM node. We try to print it out:

console.log(this.$refs.temp.$el);
Copy the code

Console

<div> I am a temporary component </div>Copy the code

As you can see from the Console, $el prints out the

2.12.3 Vue. NextTick ()

Returns the directory

Of course, we sometimes manipulate the DOM in order to manipulate the data when it changes, which is sometimes difficult to do if we use the above method.

So, what should we do?

index.html

<! DOCTYPE html> <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue learn </title> </head> <body> <! -- 2. Vue mount point -- Vue's virtual DOM is manipulated here into the actual render --> <! --> <div id="app"></div> <! -- 1. Quote Vue --> <! -- Vue CDN -- provide Vue services --> <script SRC ="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <! -- Vue Router CDN --> <script SRC ="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <! -- Axios CDN -- call interface --> <script SRC ="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>
  
  <script>
    
    var App = {
      template: `
        <div>
          <input v-if="isShow" ref="input" />
        </div>
      `,
      data: function() {
        return {
          isShow: true
        }
      },
      mounted: function() {// Want to do this after Vue actually renders the DOM to the page.$nextTick(function() {
          this.$refs.input.focus();
        })
      }
    }

    new Vue({
      el: document.getElementById('app'),
      components: {
        app: App
      },
      template: `<app/>`
    })

  </script>
</body>

</html>
Copy the code

As mentioned above, through Vue’s global API vue.nexttick (), we perform a deferred callback after the next DOM update loop. Use this method immediately after modifying the data to get the updated DOM.

This operation we can imagine the implementation process of Promise, will get a better experience.

Three practical

Returns the directory

So, with that in mind, it’s time for a simple exercise to review what we’ve learned:

  • Vue Todolist – Thousands of bone teaching articles

  • Vue Todolist – works thousands of bone code addresses

  • Vue Todolist – Power thousands of bone page demo

Four summarizes

Returns the directory

As above, we entered the basic Vue, may be friends will feel very dizzy.

Great oaks from little acorns grow, but you have to raise the foundation yourself.

More practical operation, more notes, always skilled up, refueling ~


Afterword.

If you need to store static pages such as jsliang. Top or company.jsliang. Top with Node backend support, you are advised to buy a cloud server to store them.

If partners do not know how to choose the cloud server, you can view the details or add jsliang QQ: 1741020489 consultation.



jsliangThe document library is composed of
Liang Junrongusing
Creative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.


Based on the
Lot. Om/LiangJunron…On the creation of works.


Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.