SoFunction
Updated on 2025-04-05

Deeply understand Vue's conditional rendering and list rendering

I have learned this in the past two days. I feel that there are a lot of knowledge points in conditional rendering and list rendering, and it is very important, so I will add a little note today.

Conditional Rendering

v-if

Render a whole set with v-if in < template>

When using v-if to control an element, we need to add it to this element. However, if you want to switch many elements, adding them one by one will be too troublesome. At this time, you can use < template > to wrap a group of elements and use v-if on it. The final rendering result will not contain the < template > element.

<template v-if="ok">
 <h1>Title</h1>
 <p>Paragraph 1</p>
 <p>Paragraph 2</p>
</template>

<script>
  data:{
    ok:true
  }
</script>

We can control the entire group of elements by changing the value of ok

v-else

You can use the v-else directive to represent the "else block" of v-if:

<div v-if="ok">
  Now you see me
</div>
<div v-else>
  Now you don't
</div>

The v-else element must be immediately followed by the v-if or v-else-if element—or it will not be recognized.

v-else-if

v-else-if, as the name implies, acts as the "else-if block" of v-if. Can be used in chain multiple times:

&lt;div&gt;
  &lt;p v-if="sc&gt;=90"&gt;excellent&lt;/p&gt;
  &lt;p v-else-if="sc&gt;=60"&gt;Pass&lt;/p&gt;
  &lt;p v-else="sc&lt;60"&gt;不Pass&lt;/p&gt;
&lt;/div&gt;

Similar to v-else, v-else-if must be immediately followed by the v-if or v-else-if element.

Reusable elements

Vue renders elements as efficiently as possible, usually reusing existing elements instead of rendering from scratch. Doing so has some useful benefits besides making Vue very fast. For example, if you allow users to switch between different login methods:

&lt;div class="exp"&gt;
  &lt;template v-if="loginType === 'username'"&gt;
    &lt;label&gt;Username&lt;/label&gt;
    &lt;input placeholder="Enter your username"&gt;
  &lt;/template&gt;

  &lt;template v-else&gt;
    &lt;label&gt;Email&lt;/label&gt;
    &lt;input placeholder="Enter your email address"&gt;
  &lt;/template&gt;
  &lt;input type="button" @click="btn" value="Switch"/&gt;
&lt;/div&gt;

&lt;script&gt;
  var exp=new Vue({
    el:".exp",
    data:{
      loginType:"username"
    },
    methods:{
      btn:function(){
        if(==="username"){
          ="email"
        }else{
          ="username"
        }
      }
    }
  })
&lt;/script&gt;

Then switching to loginType in the above code will not clear what the user has entered. Because both templates use the same element, <input> will not be replaced - just replace its placeholder.

Copy the above code and try it in your own browser.

Sometimes we don't want the browser to keep what we typed, so Vue provides you with a way to declare that "the two elements are completely independent - don't reuse them". Just add a key attribute with a unique value:

<template v-if="loginType === 'username'">
  <label>Username</label>
  <input placeholder="Enter your username" key="username">
</template>

<template v-else>
  <label>Email</label>
  <input placeholder="Enter your email address" key="email">
</template>

v-show

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

<h1 v-show="ok">Hello!</h1>
<script>
  data:{
    ok:false
  }
</script>

The difference is that elements with v-show are always rendered and kept in the DOM. v-show is simply toggling the CSS property display of an element.

Render as follows

<div style="display:none;"></div>

List rendering

Use v-for to correspond to an array as a set of elements

We use the v-for directive to render based on the list of options for an array. The v-for directive requires a special syntax in the form of item in items , items is an array of source data and item is an alias for array element iterations.

<div class="exp">
  <ul>
    <li v-for="item in items">{{}}</li>
  </ul>
</div>

<script>
  data:{
    items:[
      {text:"eat"},
      {text:"play"},
      {text:"game"}
    ]
  }
</script>

Rendering results

<div class="exp">
  <ul>
    <li>eat</li>
    <li>play</li>
    <li>game</li>
  </ul>
</div>

v-for also supports an optional second parameter as the index of the current item.

<div class="exp">
  <ul>
    <li v-for="item,index in items">{{index}}-{{}}</li>
  </ul>
</div>
<script>
  var exp=new Vue({
    el:".exp",
    data:{
      items:[
        {text:'eat'},
        {text:'paly'},
        {text:'game'}
      ]  
    }
  })
</script>

result

0-eat
1-paly
2-game

v-for of an object

You can also use v-for to iterate through the properties of an object.

&lt;div class="exp"&gt;
  &lt;ul&gt;
    &lt;li v-for="value in obj"&gt;{{value}}&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
&lt;script&gt;
  var exp=new Vue({
    el:".exp",
    data:{
      obj:{
        firstname:"PureView",
        lastname:"A quiet handsome man",
        age:18
      }
    }
  })
&lt;/script&gt;

result

PureView
A quiet handsome man
18

You can provide three parameters in total, the second parameter is the key name and the third is the index:

<li v-for="value,key,index in obj">{{index+1}}. {{key}}: {{value}}</li>

result

1. firstname: PureView
2. lastname: A quiet handsome man
3. age: 18

Array update detection

Variation method

Vue contains a set of mutated methods to observe arrays, so they will also trigger view updates. These methods are as follows:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

For example

<div class="exp">
  <ul>
    <li v-for="item in items">{{}}</li>
  </ul>
</div>

<script>
  var exp=new Vue({
    el:".exp",
    data:{
      items:[
        {text:"eat"},
        {text:"play"},
        {text:"game"}
      ]
  }
  })
  ({text:'watch TV'})
</script>

Reshape the array

Mutation method, as the name suggests, changes the original array called by these methods. In contrast, there are non-mutating method methods, such as: filter(), concat() and slice() . These do not change the original array, but always return a new array. When using non-mutated methods, you can replace the old array with the new array:

data:{
  items:[
      {text:"eat"},
      {text:"play"},
      {text:"game"},
      {text:"gaming"},
      {text:"wot"},
      {text:"wows"},
      {text:"wt"}
    ]
  }
}
(0,5)

Using the example in the previous section, the returned value will not change the original data, and we can see it by printing it on the console.

Things to note

Due to JavaScript limitations, Vue cannot detect arrays with the following changes:

  • When you use the index to set an item directly, for example: [indexOfItem] = newValue
  • When you modify the length of the array, for example: = newLength

In order to solve the first type of problem, the following two methods can achieve the same effect as [indexOfItem] = newValue, and will also trigger status updates:

// 
(, indexOfItem, newValue)
// 
(indexOfItem, 1, newValue)

To solve the second type of problem, you can use splice:

(newLength)

Object update detection

Due to the limitations of modern JavaScript, Vue cannot detect attribute addition or removal. For example:

var exp=new Vue({
  data:{
    a:1
  }
})
=2 //No response in the template

Vue does not allow dynamically adding new root-level properties to created instances. At this time, Vue provides a method to add attributes to the object:

(object,key,value)

Give an example

var exp=new Vue({
  el:".exp",
  data:{
    obj:{
      me:"pureview",
      pet1:"dog",
      pet2:"cat",
      hobby:"games"
    } 
  }
})

We enter the following code in the console and we can see that the data in the template has been updated.

(,"todo","eating")

In addition to adding attributes, we can also delete them

(,"pet2")

Show filter/sort results

Sometimes we want to display a filtered or sorted copy of an array without actually changing or resetting the original data. In this case, you can create computed properties that return filtered or sorted arrays.

For example, we take even numbers in an array

<div class="exp">
  <ul>
    <li v-for="n in numbers">{{n}}</li>
  </ul>
</div>

<script>
  var exp=new Vue({
    el:".exp",
    data:{
      num:[1,2,3,4,5,6,7,8,9,10]
    },
    computed:{
      numbers:function(){
        return (function(num){
          return num%2===0
        })
      }
    }
  })
</script>

Template display results:

2
4
6
8
10

In cases where computed properties do not apply (for example, in a nested v-for loop) you can use a method method:

<div class="exp">
  <ul>
    <li v-for="n in even(num)">{{n}}</li>
  </ul>
</div>

<script>
  var exp=new Vue({
    el:".exp",
    data:{
      num:[1,2,3,4,5,6,7,8,9,10]
    },
    methods:{
      even:function(num){
        return (function(num){
          return num%2===0
        })
      }
    }
  })
</script>

The result is the same

A v-for value range

v-for can also take integers. In this case, it will repeat the template multiple times.

<div>
 <span v-for="n in 10">{{ n }} </span>
</div>

result

1 2 3 4 5 6 7 8 9 10

v-for on <template>

Similar to the template v-if, you can also render blocks of multiple elements using the <template> tag with v-for.

<ul>
 <template v-for="item in items">
  <li>{{  }}</li>
  <li class="divider"></li>
 </template>
</ul>

v-for and v-if

When v-for is used with v-if, v-for has a higher priority than v-if, which means v-if will be run repeatedly in each v-for loop, respectively. This can be useful when we render nodes only for certain projects:

<li v-for="todo in todos" v-if="!">
 {{ todo }}
</li>

And if our purpose is to conditionally skip the execution of the loop, then v-if can be placed on the outer element (or < template >). like:

<ul v-if="">
 <li v-for="todo in todos">
  {{ todo }}
 </li>
</ul>
<p v-else>No todos left!</p>

v-for of component

In Vue's version 2.2.0 or above, when we want to use v-for in our components, we are not allowed to use keys

Copy the codeThe code is as follows:

<my-component v-for="(item,index) in itmes" v-bind:key="index"></my-component>

Although v-for can be used in custom components, it cannot automatically pass data into components because the components have their own independent scope. In order to pass iterative data into the component, we need to use props:

&lt;my-component v-for="(item,index) in items" v-bind:key="index" :lie=""l&gt;&lt;/my-component&gt;

&lt;script&gt;
  ('mycom', {
    template: "&lt;p&gt;{{}}&lt;/p&gt;",
    props:["lie"]
  })
  var exp=new Vue({
    el:".exp",
    data:{
      items:[
        {text:'There was a mountain once upon a time'},
        {text:'There is a temple on the mountain'},
        {text:'There is an old monk in the temple'},
        {text:'Working about Honor of Kings'}
      ]
    }
  })
&lt;/script&gt;

result

There was a mountain once upon a time
There is a temple on the mountain
There is an old monk in the temple
Playing King of Glory

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.