Vue3 [conditional rendering, list rendering, state management by key, event processing, event parameters, event modifiers, array change detection] (2) – comprehensive detailed explanation (learning summary — from entry to deepening)

About the author: Hello everyone, I am Xiaotong, a Java development engineer, a CSDN blogger, and a new star creator in the Java field
Series of columns: Front-end, Java, Java Middleware Encyclopedia, WeChat Mini Program, WeChat Payment, Ruoyi Framework, Spring Family Bucket
If there are any mistakes in the knowledge points of the article, please correct me! Learn and progress together with everyone
If you feel that the blogger’s article is not bad, pleaseSupportBlogger
The blogger is working hard to complete the 2023 plan: take dreams as horses, set sail, 2023 dream chasers

Directory

conditional rendering

v-if

v-else

v-else-if

v-show

list rendering

complex data

v-for with objects

Manage state by key

event handling

event parameters

event modifier

Array change detection

conditional rendering

In Vue, conditional rendering is provided, which is similar to conditional statements in JavaScript

v-if

v-else

v-else-if

v-show

v-if

The v-if directive is used to conditionally render a piece of content. This block will only be rendered if the directive’s expression returns true

<template>
    <div v-if="flag">Can you see me</div>
</template>
<script>
export default {
    data() {
        return {
            flag:true
       }
   }
}
</script>

v-else

You can also use v-else to add an “else block” to v-if

<template>
    <div v-if="flag">Can you see me</div>
    <div v-else>Then you still look at me</div>
</template>
<script>
export default {
    data() {
        return {
            flag: false
       }
   }
}
</script>

v-else-if

As the name implies, v-else-if provides an “else if block” that corresponds to v-if . It can be reused many times in a row

<template>
    <div v-if="type === 'A'">
       A
    </div>
    <div v-else-if="type === 'B'">
       B
    </div>
    <div v-else-if="type === 'C'">
       C
    </div>
    <div v-else>
       Not A/B/C
    </div>
</template>
<script>
export default {
    data() {
        return {
            type: "D"
       }
   }
}
</script>

v-show

Another directive that can be used to conditionally display an element is v-show . Its usage is basically the same

<template>
    <div v-show="flag">Can you see me</div>
</template>
<script>
export default {
    data() {
        return {
            flag:true
       }
   }
}
</script>

v-if vs v-show

v-if is “true” conditional rendering because it ensures that event listeners and child components inside the conditional block are destroyed and recreated when toggled.

v-if is also lazy: if the condition evaluates to false on the first render, nothing will be done. Conditional blocks are only rendered when the condition first becomes true.

In contrast, v-show is much simpler, the element will always be rendered regardless of the initial condition, and only the CSS display property will be toggled.

Overall, v-if has higher switching overhead, while v-show has higher initial rendering overhead. So, if you need to toggle frequently, v-show is better; if binding conditions rarely change at runtime, v-if is more appropriate

Real-time effect feedback

1. In Vue, the wrong description about v-if and v-show is:

A v-if is “true” conditional rendering, which ensures that event listeners and subcomponents inside the conditional block are destroyed and rebuilt when toggled

B v-if is also lazy: if the condition evaluates to false on the first render, nothing will be done. Conditional blocks are only rendered when the condition first becomes true

C v-show elements are always rendered regardless of initial conditions, only the CSS display property is toggled

D v-show has a higher toggle overhead, while v-if has a higher initial render overhead`

List Rendering

We can use the v-for directive to render a list based on an array.

The value of the v-for directive requires a special syntax of the form item in items, where items is an array of source data and item is an alias for the iterated item

<template>
    <div>
        <p v-for="item in names">{<!-- -->{ item }}</p>
    </div>
</template>
<script>
export default {
    data() {
        return {
            names:["Little Tong","Tong Xiaochun","IT"]
       }
   }
}
</script>

Complex Data

In most cases, the data source we render comes from a network request, which is in JSON format

<template>
    <div v-for="item in result">
        <p>{<!-- -->{ item. title }}</p>
        <img :src="item.avator" alt="">
    </div>
</template>
<script>
export default {
    data() {
        return {
            result: [{
                "id": 2261677,
                "title": "Ordos|Experience the bright night view of a city To experience a city, except for the busy traffic in the daytime,
                          Bustling and bustling",
                "avator": "https://pic.qyer.com/avatar/002/25/77/30/200?v=1560226451",
           },
           {
                "id": 2261566,
                "title": "This cave dark wind coffee shop in Chengdu is so cool? Walking in the morning and evening? The weather in Chengdu is so hot? Coffee? People must be",
                "avator": "https://pic.qyer.com/avatar/011/07/08/69/200?v=1572185180",
           },
           {
                "id": 2261662,
                "title": "[Xinlong in Western Sichuan - Cuoka Lake] Cuoka Lake, which means "black sea water among the rocks", is mysterious and original. Deep",
                "avator": "https://pic.qyer.com/avatar/009/88/48/58/200?v=1507386782",
           },
           ]
       }
   }
}
</script>
<style>
img{
    width: 50px;
    height: 50px;
}
</style>

v-for also supports an optional second parameter indicating the position index of the current item

<template>
    <div>
        <p v-for="(item,index) in names">{<!-- -->{ index }}:{<!-- -->{ item }}</p>
 </div>
</template>
<script>
export default {
    data() {
        return {
            names:["Little Tong","Tong Xiaochun","IT"]
       }
   }
}
</script>

You can also use of as a delimiter instead of in , which is closer to JavaScript’s iterator syntax

<div v-for="item of items"></div>

v-for with objects

You can also use v-for to iterate over all properties of an object

<template>
    <div>
        <p v-for="(value, key, index) of userInfo">{<!-- -->{ value }}-{<!-- -->{ key }}-{<!- - -->{ index }}</p>
    </div>
</template>
<script>
export default {
    data() {
        return {
          userInfo: {
                name:"iwen",
                age:20
           }
       }
   }
}
</script>

Real-time effect feedback

1. In Vue, use v-for to traverse the array, the following form is correct:

A item in items

B item for items

C item each item

D item map items

Manage state by key

By default, Vue follows the “update in place” strategy to update the list of elements rendered by v-for. When the order of data items changes, Vue does not move the order of DOM elements accordingly, but updates each element in place to ensure that they are rendered at the originally specified index position.

To give Vue a hint so that it can keep track of each node’s identity and thus reuse and reorder existing elements, you need to provide a unique key attribute for each element’s corresponding block:

<template>
    <div>
        <p v-for="(item,index) in names" :key="index">{<!-- -->{ item }}</p>
    </div>
</template>
<script>
export default {
    data() {
        return {
            names:["Little Tong","Tong Xiaochun","IT"]
       }
   }
}
</script>

Reminder

key here is a special attribute bound via v-bind

It is recommended to provide v-for with a key attribute whenever feasible. The value bound by the key is expected to be a value of a basic type, such as a string or a number type.

source of key

Please do not use index as the value of the key, we need to ensure that the unique index of each piece of data will not change

<template>
    <div v-for="(item,index) in result" :key="item.id">
        <p>{<!-- -->{ item. title }}</p>
        <img :src="item.avator" alt="">
    </div>
</template>
<script>
export default {
    data() {
        return {
            result: [{
                "id": 2261677,
                "title": "Ordos|Experience the bright night view of a city To experience a city, except for the busy traffic in the daytime, the hustle and bustle",
                "avator": "https://pic.qyer.com/avatar/002/25/77/30/200?v=1560226451",
           },
           {
               "id": 2261566,
                "title": "This cave dark wind coffee shop in Chengdu is so cool? Walking in the morning and evening? The weather in Chengdu is so hot? Coffee? People must be",
                "avator": "https://pic.qyer.com/avatar/011/07/08/69/200?v=1572185180",
           },
           {
                "id": 2261662,
                "title": "[Xinlong in Western Sichuan - Cuoka Lake] Cuoka Lake, which means "black sea water among the rocks", is mysterious and original. Deep",
                "avator": "https://pic.qyer.com/avatar/009/88/48/58/200?v=1507386782",
           },
           ]
       }
   }
}
</script>

Event Handling

We can use the v-on directive (abbreviated as @ ) to listen to DOM events and execute the corresponding JavaScript when the event is triggered. Usage: v-on:click=”methodName” or @click=”handler”

The value of the event handler can be

1 Inline event handler: An inline JavaScript statement executed when the event is triggered (similar to onclick)

2 Method event handler: a property name or path pointing to a method defined on the component

Inline event handlers

Inline event handlers are usually used for simple scenarios

<template>
    <button @click="count + + ">Add 1</button>
    <p>Count is: {<!-- -->{ count }}</p>
</template>
<script>
export default {
    data() {
        return {
            count:0
       }
   }
}
</script>

Method event handler

<template>
    <button @click="addCount">Add</button>
    <p>Count is: {<!-- -->{ count }}</p>
</template>
<script>
export default {
    data() {
        return {
            count:0
       }
   },
    // All methods or functions are placed here
    methods: {
        addCount(){
            this.count + =1
         }
   }
}
</script>

Real-time effect feedback

1. In Vue, the following methods of adding events are correct:

A onClick

B :click

C @click

D click

Event Parameters

Event parameters can get the event object and pass data through the event

Get event object

<template>
    <button @click="addCount">Add</button>
    <p>Count is: {<!-- -->{ count }}</p>
</template>
<script>
export default {
    data() {
        return {
            count:0
       }
   },
    methods: {
        addCount(e){
            e.target.innerHTML = "Add" + this.count
            this.count + =1
       }
   }
}
</script>

Pass parameters

<template>
    <button @click="addCount('hello')">Add</button>
    <p>Count is: {<!-- -->{ count }}</p>
</template>
<script>
  export default {
    data() {
        return {
            count:0
       }
   },
    methods: {
        addCount(message){
            console. log(message);
            this.count + =1
       }
   }
}
</script>

Get the contents of the list

<template>
    <p @click="getNameHandle(item)" v-for="(item,index) in names" :key="index">{<!-- -->{ item
}}</p>
</template>
<script>
  export default {
    data() {
        return {
            names:["iwen","ime","frank"]
       }
   },
    methods: {
        getNameHandle(name){
            console. log(name);
       }
   }
}
</script>

Get event while passing parameters

<template>
    <p @click="getNameHandle(item,$event)" v-for="(item,index) in names" :key="index">
    {<!-- -->{ item }}</p>
</template>
<script>
export default {
    data() {
        return {
            names:["iwen","ime","frank"]
       }
   },
    methods: {
        getNameHandle(name, e){
            console.log(name,e);
       }
   }
}
</script>

Real-time effect feedback

1. In Vue, the event object is obtained during the process of passing parameters. The correct way to write it is:

A @click=”getNameHandle(item)”

B @click=”getNameHandle(item,$event)”

C @click=”getNameHandle($event,item)”

D @click=”getNameHandle()”

event modifier

It is very common to call event.preventDefault() or event.stopPropagation() when handling an event. Although we can call it directly in the method, it would be better if the method can focus more on the data logic without having to deal with the details of DOM events

To solve this problem, Vue provides event modifiers for v-on, which are commonly used as follows:

1. stop

2. prevent

3 .once

4. enter

5…

specific reference

Address: https://cn.vuejs.org/guide/essentials/event-handling.html#event-modifiers

Block default events

<template>
    <div>
        <a @click.prevent="clickHandle" href="https://www.itbaizhan.com">Tong Xiaochun</a>
    </div>
 </template>
<script>
  export default {
    data(){
        return {
       }
   },
    methods: {
        clickHandle(){
            console. log(111);
       }
   }
}
</script>

Prevent event bubbling

<template>
    <div @click="clickDiv">
        <p @click.stop="clickP">Test bubbling</p>
    </div>
</template>
<script>
  export default {
    data(){
        return {
       }
   },
    methods: {
        clickDiv(){
            console.log("div");
       },
        clickP(){
            console.log("P");
       }
   }
}
</script>

Real-time effect feedback

1. Which of the following event modifiers is an attribute that prevents event bubbling:

A.prevent

B.stop

C .once

D.enter

Array Change Detection

How to change

Vue is able to listen to the mutating methods of reactive arrays and trigger relevant updates when they are called. These methods of change include:

push()

pop()

shift()

unshift()

splice()

sort()

reverse()

<template>
    <div>
        <p v-for="(item,index) in names" :key="index">{<!-- -->{ item }}</p>
        <button @click="clickAddNamesHandle">Add data</button>
    </div>
</template>
<script>
  export default {
    data(){
        return {
          names:["iwen","ime","frank"]
       }
   },
    methods: {
        clickAddNamesHandle(){
            this.names.push("sakura")
       }
   }
}
</script>

Replace an array

The change method, as the name suggests, is to change the original array that calls them. In contrast, there are some immutable methods, such as filter() , concat() and slice() , which do not change the original array but always return a new array. When encountering a non-changing method, we need to replace the old array with the new one

<template>
    <div>
        <h3>Array 1</h3>
        <p v-for="(item,index) in nums1" :key="index">{<!-- -->{ item }}</p>
        <h3>Array 2</h3>
        <p v-for="(item,index) in nums2" :key="index">{<!-- -->{ item }}</p>
        <button @click="filterHanedle">Merge data</button>
    </div>
</template>
<script>
  export default {
    data(){
        return {
            nums1:[1,2,3,4,5],
            nums2:[6,7,8,9,10]
       }
   },
    methods: {
        filterHanedle(){
            this.nums1 = this.nums1.concat(this.nums2)
       }
   }
}
</script>

Real-time effect feedback

1. Which of the following methods can be detected as a change method:

A push

B filter

C concat

D slice