Hello everyone, I’m Xiao CAI. A man who wants to be a man who talks architecture! If you also want to be the person I want to be, or point a concern to do a companion, let small dishes no longer lonely!

This article describes how to get started with Vue

Refer to it if necessary

If it is helpful, do not forget the Sunday

Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!

We’ve already covered the basics of webpack in the previous post, and this is just a way to pave the way for Vue! Haven’t seen friends remember jump check missing missing ~!

Back-end vision learning Webpack, both civil and military?

Vue cognitive

What is Vue? It is a set of progressive frameworks for building user interfaces. In a brief introduction, we need to focus on two words: building user interfaces and progressive frameworks. Its characteristics are embodied in two aspects

  • Data-driven view

In a page that uses a VUE, the VUE automatically listens for changes in data to render the structure of the page itself. In VUE, instead of manually manipulating the DOM nodes, it binds the DOM to the data using some special HTML syntax. Once the binding is created, the DOM is kept in sync with the data and updated whenever the data is changed

  • Two-way data binding

The data drive mentioned above is one-way binding, but VUE also supports bidirectional binding. When the page structure data occurs, the page information can be automatically synchronized to the VUE data without manipulating the DOM.

The MVVM model

The two vUE features mentioned above are based on MVVM

  • M: MOdel, which represents the data source on which the current page is rendered
  • V: VIew represents the DOM structure rendered by the current page
  • VM: ViewMOdel, for instance of vue, i.eMVVMThe core of the

Through the figure above, we can explain the working principle of MVVM. ViewModel, as the core of MVVM, is equivalent to a bridge connecting Model(data source) and View(page structure). The View is the structure you see in the browser, and the Model usually refers to the data you get through an Api call.

  • When the data source changes, the ViewModel listens and automatically updates the structure of the page based on the latest data source
  • When the value of a page element changes, the ViewModel listens and synchronizes the updated value to the Model data source

This is a very simple Vue example, but it already contains the view-ViewModel-model three-part structure

The basic use

Ⅰ, instructions,

Let’s start by recognizing what a directive is. Instructions are template syntax provided by VUE for developers to help them render the basic structure of the page

Instructions in VUE can be divided into 6 categories according to different uses, as follows:

1) Content rendering instruction

Content render instructions are used to render text content in DOM elements.

1, v - text

Two H1 tags, one with a default value and one with no default value, we used the V-text instruction for both, look at the result

Happily, v-text worked as we expected, but something was wrong. The second h1 had its own default value, which was replaced by a V-text instruction, which became a v-text weakness.

The V-text directive overrides the default values within the element

{{}}

This is the syntax provided by VUE to solve the problem of V-text overwriting the default text content value. The technical name for this {{}} syntax is interpolation. Here’s how to use it:

We can use simple syntax {{value key}} to get the data source value without interfering with the original value of the tag, so interpolation will be more common in our daily development. It also supports simple Java Script syntax in directives:

But if a value in the data source is not a value in the normal sense, but rather an HTML fragment, can {{}} successfully identify the render?

Unfortunately, interpolation does not render the HTML fragments for us, so what should we do at this point? We need to use the next instruction ~!

v-html

This directive is an obvious reference to HTML, since V-text and interpolation only help us render plain text content. If you want to render a string containing an HTML tag as an HTML element on a page, you need to use this V-HTML directive

2) Attribute binding instructions

v-bind

If you need to dynamically bind values for attributes of an element, you need to use the V-bind attribute binding directive

Because v-bind is used so often in daily development, vue officially provides a shorthand (in English 🙂

Simple JS syntax is also supported in V-bind

3) Event binding directives

Vue also provides the V-ON event binding directive, which is used to bind event listening for the DOM phase. The simple syntax is as follows

We define data sources in Data, methods in methods, and events bound by v-ON directives. The overall structure is clear, except for the onclick event. We can also use onInput, onKeyUp and other native events

Since the V-ON command is used frequently in development, the official vUE also provides a short form (@).

We have the parameter e in the above method function, I don’t know if you have noticed ~

In the native DOM event binding, the event parameter object can be received at the parameter of the event handler function. Similarly, the event parameter object can be obtained in the event handler function bound by the V-ON instruction in the same way

This is fine if the function is called without parameters, but what if there are parameters? Let’s give it a try

We can see that this method does not work, our event parameter object is overwritten! This brings us to the special variable $event that Vue provides to represent the native event parameter object. $event can solve the problem that the event parameter object is overwritten.

As you can see, this special variable has solved the problem we encountered above!

(I) Event modifier

One of the classic problems with DOM events is event bubbling. What is an event bubbling?

We can solve this problem simply by using the above mentioned event object to prevent bubbling behavior:

The event bubble problem can be solved by using the stopPropagation() function, but Vue provides a more elegant solution

This method is called event modifiers in VUE, which is used to control the triggering of events more conveniently. Here are five common event modifiers:

Event modifier instructions
.prevent Prevent default actions (a tag jump, form submission, etc.)
.stop Prevents events from bubbling
.capture Trigger the current event handler in capture mode
.once Bound events only fire once
.self The event handler is fired only if event.target is the current element itself

All usage is via @click. name

(ii) key modifier

When we monitor keyboard events, we often need to judge the detailed keys, which are used to correspond to different key actions. Of course, vue also adds key modifiers for keyword-related events, such as listening for the enter key :(replace the enter name for other keys as needed)

4) Bidirectional binding instruction

We’ve already seen instructions like V-bind/V-text/V-html / {{}}, but these are one-way binding instructions. The page element can get data from the data source, but the data source cannot get data from the page element. So, here we have the V-Model bidirectional binding instructions provided by VUE.

The advantage of bidirectional binding instructions is that you can quickly retrieve the form’s data without having to manipulate DOM elements

We can change the username in the input box input value, the corresponding, page {{username}} value will change ~!

In order to reduce unnecessary unnecessary operations when using bidirectional binding, trim, number conversion… Vue already provides us with the corresponding processing modifier:

The modifier instructions
.number Automatically converts user input values to numeric types
.trim Automatic filtering of closing whitespace characters entered by the user
.lazy Update at “change” instead of “input”
5) Conditional rendering instruction

Conditional render instructions are used to control the display and hiding of DOM nodes

  • v-if
  • v-show

The above two instructions are conditional rendering instructions, which can be used as follows:

When the condition is met, both will be displayed normally. When the condition is not met, let’s see what the difference is between the two:

We can look at the page element through the F12 console and see that the v-if modified SPAN element is missing from the page element, so we conclude:

Implementation principle level

  • The V-if directive dynamically creates or removes DOM elements to control how they are displayed or hidden on the page
  • v-showDirectives dynamically add or remove elementsstyle='display: none; 'Style to control how elements are displayed or hidden on the page

Performance consumption layer

V-if has a higher switching overhead, while V-show has a higher initial rendering overhead

  1. If frequent switching is required, use v-show
  2. If conditions rarely change at run time, use V-if

There’s a V-if tag, there’s a V-else tag, there’s a V-else tag

6) List rendering instructions

The previous bindings were single-valued elements, and when we encountered an array element we had to use the V-for tag provided by vUE. This tag is used to loop through a list structure based on an array. The V-for directive requires a special syntax in the form of item in items

  • Items: Array to loop through
  • Item: each item to be looped

In addition to the item in items syntax, index is also supported as an index -> (item, index) in items

This directive is usually accompanied by a key directive :key. Vue uses key to maintain the state of the list. When the list data changes, by default, Vue tries to reuse existing DOM elements as much as possible to improve rendering performance. The stateful list cannot be updated properly.

To give Vue a hint that it can keep track of the identity of each node to improve rendering performance while ensuring that the stateful list is properly updated. At this point, you need to provide a unique key attribute for each item!

Here are a few things to note about key:

  • keyThe value of can only bestringordigitaltype
  • keyMust have the value ofuniqueness(usually take ID)
  • useindexThe value of key has no meaning (the value of index is not unique)
  • It is recommended to usev-forThe key must be specified

ⅱ. Filter

Now that we’ve covered the six classes of directives in VUE, let’s move on to Filters in VUE.

Filters are commonly used to format text. They can be used in interpolation {{}} and v-bind as follows:

We | as pipe filter method call. Where the filter method is written under the Filters node.

This usage is reminiscent of the pipe operator operation in Linux and the stream.map operation in Java 8

The filter we defined above is a private filter. What is private? This filter can only be used in the EL region controlled by the current VM instance. If you want to share filters across multiple VM instances, you need to define global filters.

The filter also supports multiple calls in a row

The filter also supports passing parameters

Note: filters are only supported in Vue 2.x and 1.x, filters have been removed from vue 3.x.

ⅲ. Listeners

What is a listener? The Watch listener can be used to listen for changes in data and take specific actions in response to changes in data! Here’s a simple use example:

We can obtain the latest value of username by listening to the data source username in data. This method is also used to determine whether the parameter value is available, and quickly feedback to the user prompt ~! There are a few things to be aware of when using listeners

  • All listeners should be defined under the Watch node
  • A listener is essentially a function that listens for changes in data by using the name of the corresponding data as the method name
Obtaining immediate

By default, the watch listener is not invoked after the component is first loaded, and you need to use the immediate option if you want the Watch listener to be invoked immediately. In short, the immediate controls whether the listener fires automatically!

The usage is as follows:

Handler () is a fixed notation that calls the handler function automatically when the listening value changes. Immediate indicates that the current Watch listener is triggered as soon as the page is rendered

At this point, you can see from the console that the listener was triggered when the value was first bound

Denominated in deep

When the value we listen to becomes an object, can we use the above writing method to listen to the object’s property value change?

Through the console, we found that none of the subsequent changes, other than handling the first listener, triggered the listener! Then we need to use our deep property:

By adding the deep: true annotation, we can successfully listen for changes in the object’s properties. If we want to use the shorthand listener, we need to write as follows:

Note: If you want to listen for changes to child attributes of an object, you must enclose single quotes

ⅳ. Calculate attributes

Having seen the use of listeners, let’s strike while the iron is hot to understand the computing properties in VUE! What are computed attributes? To calculate an attribute is to obtain an attribute value after a series of operations. This dynamically calculated attribute value can be used by template structure or methods. A simple example is as follows:

Computing attributes itself is not complicated to use, and we need to understand several of its characteristics

  • Although the computed property is defined at the time of declaration asmethodsBut the nature of a calculated property is a property, which is used asCommon propertiesCan be used
  • The computed property caches the computed result, only the computed property dependentData changes, the calculation is recalculated

Ⅴ,

This article briefly introduces the basic usage of Vue, of course, there is a long way to go to master Vue, and we will continue to update the Vue related articles!

Don’t talk, don’t be lazy, and xiao CAI do a blowing bull X do architecture of the program ape ~ point a concern to do a companion, let xiao CAI no longer lonely. See you later!

Today you work harder, tomorrow you will be able to say less words!

I am xiao CAI, a man who grows stronger with you. 💋

Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!