Deep understanding of Vue conditional rendering and list rendering, deep understanding of vue

Source: Internet
Author: User

Deep understanding of Vue conditional rendering and list rendering, deep understanding of vue

I learned a lot about conditional rendering and list rendering in Vue. js over the past two days, and it is very important. So, add a little note today.

Conditional Rendering

V-if

Use v-if in <template> to render a whole group

When using the v-if control element, we need to add it to this element. However, it is too troublesome to add multiple elements one by one. In this case, you can use <template> to wrap a group of elements and use v-if on it. The final rendering result does not contain the <template> element.

<template v-if="ok"> 

We can change the OK value to control the entire group of elements.

V-else

You can use the v-else command to indicate 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 followed by the v-if or v-else-if element -- otherwise it will not be recognized.

V-else-if

V-else-if, as the name suggests, acts as the "else-if block" of v-if ". It can be chained for multiple times:

<Div> <p v-if = "SC> = 90"> excellent </p> <p v-else-if = "SC> = 60"> pass </p> <p v-else = "SC <60"> fail </p> </div>

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

Reusable elements

Vue renders elements as efficiently as possible. It usually reuses existing elements instead of rendering them from the beginning. In this way, in addition to making Vue very fast, there are also some useful benefits. For example, if you allow users to switch between different logon methods:

<Div class = "exp"> <template v-if = "loginType = 'username'"> <label> username </label> <input placeholder = "Enter your Username "> </template> <template v-else> <label> Email </label> <input placeholder =" Enter your email address "> </template> <input type =" button "@ click =" btn "value =" "/> </div> <script> var exp = new Vue ({el: ". exp ", data: {loginType:" username "}, methods: {btn: function () {if (this. loginType = "username") {this. loginType = "email"} else {this. loginType = "username" }}}) </script>

In the above Code, switching loginType will not clear the content already entered by the user. Because the two templates use the same element, <input> will not be replaced -- it is just replaced with its placeholder.

Copy the above Code and try it in your browser.

Sometimes we do not want the browser to retain the content we input, so Vue provides you with a way to declare that "these two elements are completely independent-do not reuse them ". You only need to 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

The other option used to display elements based on conditions is the v-show command. The usage is roughly the same:

The difference is that elements with v-show are always rendered and kept in the DOM. V-show is a simple way to switch the CSS attribute display of an element.

Rendering is as follows:

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

List rendering

Use v-for to map an array to a group of elements.

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

<div class="exp">  <ul>    <li v-for="item in items">{{item.text}}</li>  </ul></div><script>  data:{    items:[      {text:"eat"},      {text:"play"},      {text:"game"}    ]  }</script>

Rendering result

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

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

<div class="exp">  <ul>    <li v-for="item,index in items">{{index}}-{{item.text}}</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 attributes of an object.

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

Result

PureView
A quiet handsome man
18

You can provide a total of three parameters, the second parameter is the key name, and the third parameter 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

Mutation Method

Vue contains a set of Variation methods for the observed array, so they will also trigger view update. These methods are as follows:

  • Push ()
  • Pop ()
  • Shift ()
  • Unshift ()
  • Splice ()
  • Sort ()
  • Reverse ()

For example

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

Remodeling Array

Mutation method, as its name implies, changes the original array called by these methods. In contrast, there are also non-mutating methods, such as filter (), concat (), and slice (). These will not change the original array, but will always return a new array. When using the non-Variant Method, 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"}    ]  }}exp.items.slice(0,5)

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

Notes

Due to JavaScript restrictions, Vue cannot detect the following changed Arrays:

  • When you use indexes to directly set an item, such as vm. items [indexOfItem] = newValue
  • When you modify the length of an array, for example, vm. items. length = newLength

To solve the first type of problem, either of the following methods can achieve the same effect as vm. items [indexOfItem] = newValue, or trigger status update:

// Vue.setVue.set(exp.items, indexOfItem, newValue)
// Array.prototype.spliceexp.items.splice(indexOfItem, 1, newValue)

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

exp.items.splice(newLength)

Object update Detection

Due to restrictions of modern JavaScript, Vue cannot detect attribute addition or deletion. For example:

Var exp = new Vue ({data: {a: 1}) vm. B = 2 // no response in the template

Vue cannot dynamically add new root-level attributes to created instances. In this case, Vue provides a method to add attributes to an object:

Vue.set(object,key,value)

For example

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

Enter the following code in the console to see that the data in the template has been updated.

Vue.set(exp.obj,"todo","eating")

In addition to adding properties, you can also delete them.

Vue.delete(exp.obj,"pet2")

Display filtering/sorting results

Sometimes we want to display an array of filtered or sorted copies without actually changing or resetting the original data. In this case, you can create calculation attributes for the returned filter or sort array.

For example, we can retrieve its even number 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 this.num.filter(function(num){          return num%2===0        })      }    }  })</script>

Template display result:

2
4
6
8
10

If the calculation attribute is not applicable (for example, in a nested v-for loop), you can use a 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 num.filter(function(num){          return num%2===0        })      }    }  })</script>

The results are the same.

A value range of v-

V-for can also be an integer. In this case, it repeats 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 use the <template> label with v-for to present blocks with multiple elements.

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

V-for and v-if

When v-for and v-if are used together, v-for has a higher priority than v-if, this means that v-if will run in each v-for loop. This may be useful when we only render nodes for some projects:

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

If we want to conditionally skip loop execution, we can place v-if on the outer element (or <template>. For example:

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

Component v-

In Vue 2.2.0 or later versions, keys are not allowed when we use v-for in components.

Copy 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 a custom component, it cannot automatically transmit data to the component because the component has its own scope. To pass iterative data to components, we need to use props:

<My-component v-for = "(item, index) in items" v-bind: key = "index": lie = "item. text "l> </my-component> <script> Vue. component ('mycom', {template: "<p >{{ this. lie }}</p> ", props: [" lie "]}) var exp = new Vue ({el :". exp ", data: {items: [{text: 'previous Mountain '}, {text: 'Temple on Mountain'}, {text: 'old monk in temple '}, {text: 'playing glory of kings '}] }}) </script>

Result

Previously there was a mountain
Temple in the mountains
An old monk in the temple
Playing the glory of the king

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.