Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue computing properties, event monitoring and conditional rendering example analysis

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "Vue computing properties, event monitoring and conditional rendering instance analysis", with detailed content, clear steps and proper handling of details. I hope that this article "Vue computing properties, event monitoring and conditional rendering instance analysis" can help you solve your doubts.

Basic syntax 1, interpolation (dynamic content) Mustache syntax (double curly braces)

Insert the text data from the data into the HTML, where the data is responsive.

Message: {{msg}} {{firstName}} {{lastName}} {{firstName+lastName}} {{firstName+ "+ lastName}} / using the JavaScript expression {{counter*2}} {{number + 1}} {{ok? 'YES':' NO'}} {{message.split (''). Reverse (). Join (')} instruction

V-once: perform one-time interpolation. When the data changes, the contents of the interpolation will not be updated.

This will not change: {{msg}}

V-html: parse html and show

V-text: render the content text of the specified dom, similar to Mustache. It is generally not used and is not flexible enough. It will overwrite all the content in the tag.

V-pre: display the tag content intact without parsing

{{message}}

Result: {{message}}

V-cloak: resolving vue parsing stutters will appear {

{}} flickering problem

Before vue parsing, p has the attribute v-cloak, which is not available after parsing.

So you can hide the uncompiled Mustache tags through this directive until the instance is ready

{{message}}

[v-cloak] {display:none;} 2, binding properties (dynamic properties)

V-bind is used to bind one or more property values or to pass props values to another component. Abbreviated as colon:

1. Src and href of the element

Baidu 2, class binding

Object syntax

We can pass an object to v-bind:class to switch class dynamically

The above syntax indicates that the existence of the class active will depend on the truthiness of the data property isActive.

You can dynamically switch between multiple class by passing in more fields in the object. In addition, the v-bind:class instruction can also coexist with a normal class attribute.

Data: {isActive: true, hasError: false}

The result is rendered as follows:

When the isActive or hasError changes, the class list is updated accordingly. For example, if the value of hasError is true,class, the list becomes "static active text-danger".

Bound data objects do not need to be defined inline in the template, but can also be defined in the data

Data: {classObject: {active: true, 'text-danger': false}}

The result of the rendering is the same as above. We can also bind a computed property of the returned object here.

Data: {isActive: true, error: null}, computed: {classObject: function () {return {active: this.isActive & &! this.error, 'text-danger': this.error & & this.error.type = =' fatal'}

The method that returns the object

Data: {isActive: true, error: null}, methods: {IsActive () {return {active: this.isActive & &! this.error, line:isLine}

Array syntax

We can pass an array to v-bind:class to apply a class list:

Data: {activeClass: 'active', errorClass:' text-danger'}

Render as:

Depending on the class in the conditional switching list, you can use a ternary expression:

Writing like this will always add errorClass, but only if isActive is truthy [1].

However, it is a bit tedious to write this when there are multiple conditional class. So you can also use object syntax in array syntax:

3. Style binding inline style

Object syntax

The object syntax of v-bind:style is straightforward-- it looks a lot like CSS, but it's actually a JavaScript object. CSS property names can be named with humps (camelCase) or dash delimited (kebab-case, remember to be enclosed in quotation marks):

Data: {activeColor: 'red', fontSize: 30}

It is usually better to bind directly to a style object, which makes the template clearer:

Data: {styleObject: {color: 'red', fontSize:' 13px'}}

Similarly, object syntax is often used in conjunction with the computed properties of the returned object. Or the method.

/ / calculation attributes

/ / method

Array syntax

V-bind:style 's array syntax can apply multiple style objects to the same element:

3. Calculation attribute

Putting too much logic in the template will make the template too heavy and difficult to maintain, and the data needs to be changed before it is displayed.

{{message.split (') .reverse () .join (')}}

Basic example

Original message: "{{message}}"

Computed reversed message: "{{reversedMessage}}"

Var vm = new Vue ({el:'# example', data: {message: 'Hello'}, computed: {/ / calculate attribute getter reversedMessage: function () {/ / `this` points to vm instance return this.message.split (''). Reverse (). Join (')}})

Results:

Original message: "Hello"

Computed reversed message: "olleH"

Here we declare a calculation property reversedMessage. The function we provide will be used as the getter function of property vm.reversedMessage:

Console.log (vm.reversedMessage) / / = > 'olleH'vm.message =' Goodbye'console.log (vm.reversedMessage) / / = > 'eybdooG'

You can open the browser console and modify the vm in the example. The value of vm.reversedMessage always depends on the value of vm.message.

You can bind calculation properties in a template just like you would bind a normal property. Vue knows that vm.reversedMessage depends on vm.message, so when vm.message changes, all bindings that depend on vm.reversedMessage are updated. And best of all, we've created this dependency declaratively: the getter function that evaluates properties has no side effect, which makes it easier to test and understand.

Calculate the getter and setter of the attribute

By default, the calculation attribute is only getter, which is read-only, but you can also provide a setter when needed:

/ /... computed: {fullName: {/ / getter get: function () {return this.firstName +'+ this.lastName}, / / setter set: function (newValue) {var names = newValue.split ('') this.firstName = names [0] this.lastName = names [names.length-1]}} / /.

Now when you run vm.fullName = 'John Doe', setter will be called and vm.firstName and vm.lastName will be updated accordingly.

Because the calculated property generally does not have a setter, it is abbreviated to

FullName: function () {return this.firstName +'+ this.lastName}

Vs method for calculating attributes

The same effect can be achieved by calling a method in an expression

Reversed message: "{{reversedMessage ()}}"

/ / in the component methods: {reversedMessage: function () {return this.message.split ('') .reverse () .join ('')}}

The end result of the two approaches is indeed exactly the same. The difference, however, is that computational properties are cached based on their responsive dependencies. They are re-evaluated only when the correlation response dependency changes. This means that as long as the message has not changed, multiple visits to the reversedMessage calculation property will immediately return the previous calculation results without having to execute the function again.

This also means that the following calculation properties will no longer be updated, by contrast, whenever a re-rendering is triggered, the calling method will always execute the function again.

Calculation property vs snooping property

Vue provides a more general way to observe and respond to data changes on Vue instances: listening for properties.

{{fullName}}

Var vm = new Vue ({el:'# demo', data: {firstName: 'Foo', lastName:' Bar', fullName: 'Foo Bar'}, watch: {firstName: function (val) {this.fullName = val +''+ this.lastName} LastName: function (val) {this.fullName = this.firstName +'+ val}}

The above code is imperative and repetitive. Compare it with the version of the calculated property:

Var vm = new Vue ({el:'# demo', data: {firstName: 'Foo', lastName:' Bar'}, computed: {fullName: function () {return this.firstName +'+ this.lastName}) Computing attributes pass parameters

The calculation attribute itself cannot pass parameters, but it can be passed through closures, but there is no cache mechanism after passing parameters, which is no different from methods, so this is not introduced on the official website.

Computed: {usertype () {return function (value) {var user =''value = = 1? User = 'student': user = 'teacher' return user}} 4, basic event monitoring

You can use the v-on instruction to listen for DOM events and run some JavaScript code when triggered. Abbreviation @ click

Many event handling logic is more complex, so v-on can also receive a method name that needs to be called

Add 1 +-

The button above has been clicked {{counter}} times.

Var example1 = new Vue ({el:'# example-1', data: {counter: 0}, methods: {increment () {this.counter++}, decrement () {this.counter--;}}) parameter problem (parenthesis problem)

1. No parameter

GreetGreet

2. Have reference

Greet Greet

When only an event object is needed

one hundred and eleven

When you need an event object, as well as other objects, you can pass it into the method with the special variable $event:

Submit methods: {warn: function (message, event) {/ / now we can access the native event object if (event) {event.preventDefault ()} alert (message)}}

Several wrong writing methods

111111 event modifier

Calling event.preventDefault () or event.stopPropagation () in an event handler is a very common requirement. Although we can easily do this in the method, it is better that the method has pure data logic rather than dealing with the details of the DOM event.

To solve this problem, Vue.js provides event modifiers for v-on. As mentioned earlier, modifiers are represented by instruction suffixes that begin with a dot.

.

1. Event modifier

.stop to prevent the event from bubbling, call event.stopPropagation

. prevent blocks the default behavior of the event, calling event.preventDefault ()

The callback is triggered only when the element bound to the .self event is triggered.

...

The once event can only be triggered once, but not the second time.

Unlike other modifiers that only work on native DOM events, .once modifiers can also be used on custom component events

.native turns a vue component into a normal html so that it can listen for native events such as click, and listen for native events of the component.

Ok

.passive can improve the performance of the mobile terminal.

Do not use .passive with .passient, because .passient will be ignored and browsers may show you a warning. Remember,. Passive will tell the browser that you do not want to block the default behavior of the event.

...

.capture

...

When using modifiers, order is important; the corresponding code is generated in the same order. Therefore, using v-on:click.prevent.self will block all clicks, while v-on:click.self.prevent will only block clicks on the element itself.

Do not use .passive with .passient, because .passient will be ignored and browsers may show you a warning. Remember,. Passive will tell the browser that you do not want to block the default behavior of the event.

5. The basis of conditional rendering

The v-if directive is used to render a piece of content conditionally. This piece of content will only be rendered when the instruction expression returns a truthy value.

Display when Vue is awesometellisShow is false

Render groups using v-if conditions on elements

Because v-if is an instruction, it must be added to an element. But what if you want to switch multiple elements? At this point, you can treat an element as an invisible wrapper element and use v-if on it. The final rendering will contain no elements.

Title

Paragraph 1

Paragraph 2

V-else-if is not commonly used, it is better to use computational properties.

A B C Not A/B/C

Elements with v-if or v-else-if must also be immediately followed by elements similar to VMELLETHERMAL vMUSEL if.

Managing reusable elements with key

Vue renders elements as efficiently as possible, usually reusing existing elements rather than rendering from scratch. In addition to making Vue very fast, this has some other benefits. For example, if you allow users to switch between different login methods:

Username Email

Problem: then switching loginType in the above code will not erase what the user has already typed.

Reason: both templates use the same element, and when virtual DOM is rendered, it will not be replaced for performance reasons, just its placeholder.

Solution: add a key attribute with a unique value. The key is different and will not be reused.

Username Email

Note that elements are still reused efficiently because they do not add key attribute.

V-show

Another option for displaying elements based on conditions is the v-show directive. The usage is roughly the same:

Hello!

The difference is that elements with v-show are always rendered and retained in DOM. V-show simply toggles the element's CSS attribute display.

Note that v-show does not support elements, nor does it support v-else.

V-if vs v-show

V-if is a "real" conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during switching.

V-if is also lazy: if the condition is false at the initial rendering, nothing is done-- the conditional block does not start to be rendered until the condition becomes true for the first time.

V-show, by contrast, is much simpler-the element is always rendered regardless of the initial condition, and is simply switched based on CSS, and when the condition is false, the element's display property is set to none.

In general, v-if has higher switching overhead, while v-show has higher initial rendering overhead.

Therefore, it is better to use v-show if you need to switch very frequently, or v-if if the conditions rarely change at run time.

It is not recommended to use both v-if and v-for. When v-if is used with v-for, v-for has a higher priority than v-if.

6. List rendering 6.1 traversal array

Using v-for to map an array to a set of elements, the v-for instruction requires a special syntax in the form of item in items, where items is the source data array and item is the alias of the array element being iterated.

{{item.message}} var example1 = new Vue ({el:'# example-1', data: {items: [{message: 'Foo'}, {message:' Bar'}]}})

Results:

Foo

Bar

In the v-for block, we can access the property of all parent scopes. V-for also supports an optional second parameter, the index index of the current item.

{{parentMessage}-{{index}}-{{item.message}} var example2 = new Vue ({el:'# example-2', data: {parentMessage: 'Parent', items: [{message:' Foo'}, {message: 'Bar'}]}})

Results:

Parent-0-Foo

Parent-1-Bar

You can also use of instead of in as the delimiter because it is closer to the syntax of the JavaScript iterator:

6.2 traversing objects

You can also use v-for to traverse the property of an object.

{{value}} {{name}}: {{value}}

{{index}}. {{name}}: {{value}}

New Vue ({el:'# v Franz for Mustco objects, data: {object: {title: 'How to do lists in Vue', author:' Jane Doe', publishedAt: '2016-04-10'})

Results:

How to do lists in Vue

Jane Doe

2016-04-10

Title: How to do lists in Vue

Author: Jane Doe

PublishedAt: 2016-04-10

\ 0. Title: How to do lists in Vue

1. Author: Jane Doe

2. PublishedAt: 2016-04-10

When traversing an object, it traverses according to the result of Object.keys (), but there is no guarantee that its results will be consistent under different JavaScript engines.

6.3 maintenance status (key attribute)

When Vue is updating the list of elements rendered with v-for, it defaults to the Update in place policy. If the order of the data items is changed, Vue does not move the DOM elements to match the order of the data items, but updates each element in place and ensures that they render correctly at each index location (related to the virtual DOM and Diff algorithms).

This default mode is efficient, but only for list rendered output that does not depend on the subcomponent state or temporary DOM state (for example, form input values).

To give Vue a hint so that it can track the identity of each node, thereby reusing and reordering existing elements, you need to provide a unique key attribute for each item:

It is recommended that you provide key attribute when using v-for whenever possible, unless traversing the output DOM content is very simple, or deliberately relies on the default behavior for performance improvement. Because it is a common mechanism for Vue to identify nodes, key is not specifically associated with v-for.

Instead of using values of non-basic types such as objects or arrays as the key of v-for, use values of string or numeric types.

6.4 Array update detection change method (which methods of the array are responsive)

Changing methods changes the original array in which these methods are called

Vue wraps the change methods of the listening array, so they will also trigger view updates. These packaged methods include:

Push () plus element, this.names.push ("aaa", "bbb")

Pop () deletes the last element of the array, names.pop ()

Shift () deletes the first element of the array

Add elements at the top of the unshift () array

Splice () Delete / insert / replace elements

The first parameter is where to start deleting / inserting / replacing elements

Delete elements: the second parameter is passed in the number of elements to be deleted. If you do not pass, delete all subsequent elements splice (0mem2)

Replacement element: the second element is passed in several elements to be replaced, followed by the element splice for replacement.

Insert element: the second element is passed in 0, followed by the element splice to be inserted.

Sort the sort () array

Reverse () flip array

Substitution array (higher order functions filter, map, reduce)

Non-altered methods, such as filter (), concat (), and slice (). They do not change the original array, but always return a new array. You might think that this will cause Vue to discard the existing DOM and re-render the entire list. Fortunately, this is not the case. Vue implements some intelligent heuristics to maximize the reuse of DOM elements, so it is very efficient to replace the original array with an array containing the same elements.

Due to the limitations of JavaScript, Vue cannot detect changes in arrays and objects. There are related discussions in the in-depth response principle.

Filter () displays the filtered / sorted results

The callback function must return a Boolean value:

When true is returned, the n of this callback is automatically added to the new array inside the function; when false is returned, the n of this callback is filtered out.

Sometimes we want to display a filtered or sorted version of an array without actually changing or resetting the original data. In this case, you can create a calculated property to return the filtered or sorted array. For example:

{{n}} data: {numbers: [1,2,3,4,5]}, computed: {evenNumbers: function () {return this.numbers.filter (function (number) {return number% 2 = 0})}}

You can use a method where the calculation property is not applicable (for example, in a nested v-for loop):

{{n}} data: {sets: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]}, methods: {even: function (numbers) {return numbers.filter (number) {return number% 2 = 0})}}

Map () mapping

Let nums= [1, 2, 3, 4, 5] let nuwnums=nums.map (function (n) {return nasty 2})

Summary of elements in the reduce array

Let nums= [1,2,3,4,5] / preValue is the previous value, 0 is the initial default value; n is the element let nuwnums=nums.reduce (function (preValue,n) {return preValue+n}, 0) in the array

[use value range in v-for]

V-for can also accept integers. In this case, it will repeat the template for the corresponding number of times.

{{n}}

Results:

1 2 3 4 5 6 7 8 9 10

Use v-for on the

Similar to v-if, you can also use v-for to cycle through a piece of content that contains multiple elements. For example:

{{item.msg}}

V-for is used with v-if

Note that we do not recommend using v-if and v-for on the same element.

When they are on the same node, v-for has a higher priority than v-if, which means that v-if will be run repeatedly in each v-for loop.

7. Basic use of form input binding v-model

Realize the two-way binding of form elements and data

Message is: {{message}}

Data: {message:''}

Principle

Message is: {{message}}

Data: {message:''}, methods: {valueChange (event) {this.message=$event.target.value;}}

Abbreviation:

V-model internally uses different property for different input elements and throws different events:

Text and textarea elements use value property and input events

Checkbox and radio use checked property and change events

The select field has value as the prop and change as the event.

Radio radio box

The gender of your choice is {{sex}} data: {sex:' female'}

Sex in data is the default, and its radio button is also selected by default because of two-way binding

Mutually exclusive radio buttons: v-model or name= "sex" in a group

Checkbox check box

Single check box, bound to Boolean value

Agree to the agreement whether to agree to the agreement {{isAgree}} next step data: {isAgree:false}

Checkboxes, binding to array

Basketball and football data: {hobbies: []}

Select selection box

Radio

The fruit chosen by apple and banana is {{fruit}} data: {fruit:''}

Multiple selection

The fruit chosen by apples and bananas is the {{fruits}} data: {fruits: []} modifier

The view is updated when the cursor leaves after the input box is finished.

.trim filter leading and trailing spaces

.number automatically converts the user's input value to a numeric type. If you enter a number first, it will restrict you to enter a number; if you enter a string first, it is tantamount to not adding. Number

The usage is as follows:

There are many modifiers such as keyboard, mouse and so on.

After reading this, the article "Vue computing properties, event monitoring and conditional rendering instance analysis" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report