banner
Chenh

Chenh

Frontend

Vue#

  1. Vue is a front-end framework focused on the "view layer" of web pages.
  2. Vue is a framework that uses JavaScript to manipulate a registered view component.
  3. Vue already has many excellent features.
<html>
  <div id="app">{{message}}</div>
	<script>
  	new Vue({
      el: '#app',
      data: {
        message: 'hello world!'
      }
    })
  </script>
</html>

The above is a typical minimal HTML framework of Vue.

Vue takes over the entire div block with the id of app, and Vue will operate on this block.

{{message}} is a syntax that HTML cannot recognize, but since the entire div block is handed over to Vue for processing, Vue can recognize it.

Lifecycle Diagram#

38f1ae8d348143898b42d602b049b4c4

1. Creation Phase (beforeCreate, created)#

Before created#

We find that in the above HTML code, we used the "{{}}" double curly braces syntax template, which, as we all know, does not exist in HTML. Let's take a look at the el: '#app' parameter passed when creating a new Vue instance. Yes, we have handed over the entire div with the id of app to Vue for management. We are using Vue to operate on this div with the id of app (professionally speaking, the DOM), hence the documentation of Vue states: The core library of Vue focuses only on the view layer.

Therefore, during the creation phase (before created), Vue initializes the passed div, data, and methods, etc. In other words, it prepares for the next steps.

2. Mounting Phase (beforeMount, mounted):#

From created to beforeMount#

During the transition from created to beforeMount, something remarkable happens—Vue transforms the div with the id of app into something that seems sophisticated, called an Abstract Syntax Tree (AST). But why convert it into an AST?

(Haha, this question can be answered with a little thought; readers can pause for a moment before continuing with the article.)

Because this way, Vue can understand the double curly braces syntax template we wrote in HTML, as well as the v-bind, v-for, v-if added in the tags, and even custom tags, etc. The div we wrote with the id of app—

<div id="app">
  <p>
    {{message}}
  </p>
</div>

After conversion to AST, it looks like this—

{
	  tag: "div",
	  type: 1,
	  staticRoot: false,
	  static: false,
	  plain: true,
	  parent: undefined,
	  attrsList: [],
	  attrsMap: {},
	  children: [
		  {
			  tag: "p",
			  type: 1,
			  staticRoot: false,
			  static: false,
			  plain: true,
			  parent: {
				  tag: "div",
				  type: 1,
				  staticRoot: false,
				  static: false,
				  plain: true,
				  parent: undefined,
				  attrsList: [],
				  attrsMap: {},
			  },
			  attrsList: [],
			  attrsMap: {},
			  children: [
				  {
					  type: 2,
					  text: {{message}},
					  static: false,
					  expression: "_s(message)"
				  }
			  ]
		  }
	  ]
  }

We can see that this so-called Abstract Syntax Tree (AST) is just a JavaScript object that contains all the necessary information. Vue's transformation allows JavaScript to easily manipulate these variables and replace the variables in the double curly braces with data from the data object.

From beforeMount to mounted#

However, the browser cannot understand this AST, so during the transition from beforeMount to mounted, Vue converts the AST back into HTML code. In other words, after mounted is complete, the template syntax

<div id="app">
  <p>
    {{message}}
  </p>
</div>

has been transformed into

<div id="app">
  <p>
    Hello world!
  </p>
</div>

3. After Mounting (beforeUpdate, updated):#

At this point, the famous Virtual DOM finally makes its appearance. Let's first take a look at what the Virtual DOM roughly looks like—

{
  tag:'div',		// Element tag
  attrs:{				// Attributes
    id:'app'
  }
  children:[
  {tag:'p',...}	// Child elements
  ]
}

(As you can see, it is also a JavaScript object that describes nodes through key-value pairs, but do not confuse it with the AST; these are products of two different stages.)

Now, let's think about why we need a Virtual DOM—modern web applications constantly change state during runtime, which could be due to user clicks or an axios request. These actions are asynchronous. Whenever the state changes, a re-render is required.

Do we really need to delete the entire DOM and re-render it every time a change occurs?

Let's take a look at the size of the real DOM—

f480f0266f92495fad318b96f795af7c

A single div element contains so much information, and doing so would undoubtedly be a huge cost.

Thus, we hope to detect which DOM elements have changed and update only those elements, which can greatly optimize performance. Each major framework has its own solution; Angular.js uses dirty checking, which we will not discuss here. React.js and Vue.js use the Virtual DOM.

The following diagram illustrates the specific process of the Virtual DOM.

85bfe12993624cd09c1aff049ce99428

From this diagram, we can understand when beforeUpdate and updated are triggered in Vue's lifecycle. In summary, the Virtual DOM serves as a comparison tool to identify differences and selectively replace and render elements to achieve performance optimization.


4. Destruction Phase (beforeDestroy, destroyed):#

This is the destruction phase when the Vue instance is no longer in use. The specific details have been described in great detail in the initial image, so we will not elaborate further.#

Now let's talk about Vue's reactive data binding.
What is reactive data binding?
Reactive data binding means that when the data in the data object is modified, the page view also changes accordingly, and this is achieved without refreshing the page.

How does Vue accomplish this?
To modify the view after data changes, the first step is to listen for changes.

  1. Detecting changes:
    Those who have studied JavaScript in depth will know that there are two methods to detect changes in JavaScript objects: Object.defineProperty and ES6's Proxy (if there are any unclear points, we will not discuss the specific usage here; generally, in Object.defineProperty, when the passed object is read, it triggers the get callback, and when the passed object is modified, it triggers the set callback. ES6's Proxy is a source programming capability provided by JavaScript that can directly detect changes in objects.)

  2. Notifying changes:
    After detecting which data has changed through a series of codes, the next step is to notify the places using this data, hoping that these places will use the new data. Directly notifying the DOM? In Vue 1.x, this was indeed how it was done, but this precision comes at a cost; dependency tracking incurs significant memory overhead. Therefore, Vue introduced something called Watcher. When data changes, it first notifies the Watcher, which then notifies the places using this data. Each Vue component, which is essentially a Vue instance, has a Watcher that manages everything uniformly, achieving optimization.

3cd8e6335afd4d9c87b39a60b06e1446

PS: It's actually quite simple, right? Just listen for data changes and notify the places using this data. However, there is one noteworthy point: if the array data changes, neither Object.defineProperty nor ES6's Proxy can listen to it. Therefore, changes in arrays are monitored by constructing an interceptor in the Array prototype. Whenever one of the six array methods is used, it can be intercepted and monitored, achieving the goal of listening for data changes.

Summary
In each of the steps mentioned above, Vue does a lot of work, from converting HTML code to AST, to rendering the Virtual DOM, to the diff algorithm, and various API implementations. The source code has many interesting aspects, using function currying to optimize speed, employing optimizers in the abstract syntax tree to avoid modifying unchanged DOM elements, and more, including the principles of v-if, v-for, filters, etc. Understanding some of these can greatly help you write better Vue code.

————————————————
Copyright Statement: This article is an original piece by CSDN blogger "I am Li Wen (living)", following the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement when reprinting.
Original link: https://blog.csdn.net/qq_45963949/article/details/124575471

Using Vue#

Text Binding#

  • {{variable}} Defined inside the tag, interpolation binding
  • v-text='variable' Defined in the tag attribute, binding the element's text content to the variable
  • v-html='variable' Defined in the tag attribute, binding the element's tag content to the variable

Attribute Binding#

Bind the element's attribute value to the variable in a one-way manner; when the attribute value changes, the variable will also change.

  • v-bind='variable' / ='variable'
<div>
  <input type="text" :value="info">
  <input type="text" v-bind:value="info">
  <a :href="url">Hyperlink</a>
  <img :src="imageName" alt="">
</div>
<script src="../vue.js"></script>
<script>
	new Vue({
    el:'div',
    data:{
      info:"Attribute Binding",
      url:'http://www.baidu.com',
      imageName:'head.jpg'
    }
  })
</script>

Two-way Binding#

Defined in the tag attribute, allowing the value of the tag control to be two-way bound to the variable, affecting each other synchronously.

  • v-model='variable'
<div id="app">
  <input type="text" v-model='info'>
  {{info}}
  <h1>
    Registration Form
  </h1>
  <form action="">
    Username: <input type="text" v-model="user.username"><br>
    Password: <input type="password" v-model="user.password"><br>
  </form>
  <script src="../vue.js"></script>
  <script>
  	let v = new Vue({
      el:"#app",
      data:{
        info:"Two-way Binding",
        user:{
          username:"",
          password:""
        }
      }
    })
  </script>
</div>

Event Binding#

Bind the element's events to functions.

Mouse click example: v-on:click="func" or @click="func"

<div id="app">
  <input type="button" value="bt1" @click='f()'>
  <input type="button" value="bt2" v-on:click='f()'>
</div>
<script src="../vue.js"></script>
<script>
	let v = new Vue({
    el:"div",
    data:{},
    methods:{
      f:function(){
        console.log("Button clicked!");
      }
    }
  })
</script>

Iteration#

Automatically generate the same elements based on the number of members in the bound object.

  • v-for="(variable,i) in vars"
<table>
  <caption>Car List</caption>
  <tr>
  	<th>Number</th><th>Brand Name</th><th>Price</th><th>Type</th>
  </tr>
  <tr v-for="(car,i) in arr">
  	<td>{{i+1}}</td>
    <td>{{car.name}}</td>
    <td>{{car.price}}</td>
    <td>{{car.type}}</td>
  </tr>
</table>
<script src="../vue.js"></script>
<script>
	let v=new Vue({
    el:"table",
    data:{
      arr:[	{name:'a',price:50000,type:'car1'},
          	{name:'b',price:60000,type:"car2"},
    				{name:'c',price:40231,type:'car3'}]
    }
  })
</script>

Conditional Rendering#

Bind the display state of the element to a variable; true shows, false hides.

  • v-if="variable" and v-else
<div id="app">
  <h1 v-if="isVisible">
    Title can be adjusted for display
  </h1>
  <h1 v-else>
    Otherwise, display this content
  </h1>
</div>
<script src="../vue.js"></script>
<script>
	let v=new Vue({
    el:'div',
    data:{
      isVisible:true
    }
  })
</script>

Tips#

  1. property attribute The former is the inherent property of the tag, while the latter is the k-v key-value pair defined within the tag.
  2. npm root -g Check the global plugin path.

CSS#

Positioning#

  • static

    Default document flow positioning, from top to bottom, from left to right.

  • relative

    Positioning relative to its normal document flow; its occupied space does not change, but it has a certain offset.

  • fixed

    Positioning relative to the ==browser window==; it does not move with page scrolling.

  • absolute

    Absolute positioning is relative to a positioned parent element or the HTML element.

    Absolute positioning removes the element from the document flow, does not occupy document flow space, and can overlap.

  • sticky

    Sticky positioning allows the element to switch between relative and fixed, achieving the effect of "scrolling to a certain range, the element sticks to the page."

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.