• This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

【 Draw at the end of article 】

The list of rendering

Render elements multiple times based on the data using the V-for directive.

Use arrays in V-for

Items: array of source data

Item: alias of an array element

Index: Optional. The index has access to all attributes of the parent scope

<ul id="app">
  <li v-for="(person, index) in persons">
    {{ index }}---{{ person.name }}---{{ person.age }}
  </li>
</ul>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    persons: [{name: 'very'.age: 18 },
      { name: 'thought,'.age: 20 },
      { name: 'brother'.age: 22 },
      { name: 'Ming'.age: 88},]}})Copy the code

We can use of instead of in as a separator because it is closer to the iterator syntax:

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

Use objects in V-for

Usage: (value, key, index) in Object Parameter: value: Object value key: optional, key name index: optional, index

<ul id="app">
  <li v-for="(value, key, index) in shan">
    {{ value }}
  </li>
</ul>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    shan: {
      name: 'the Chinese fir.age: 18.height: '163cm'}}})Copy the code

Use numbers in V-for

N in num Parameter: n: a number, starting from 1

<div>
  <span v-for="n in num">{{ n }} </span>
</div>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    num: 10}})Copy the code

Use strings in v-for

Usage: STR in string Parameter: STR: string, each in the source data string

<div>
  <span v-for="str in string">{{ str }} </span>
</div>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    string: 'shanshan'}})Copy the code

Loop through a section of content that contains multiple elements

You can use the Template element to loop through a section of content that contains multiple elements

<ul id="app">
  <template v-for="person in persons">
    <li>{{ item.msg }}</li>
    <li>Ha ha</li>
  </template>
</ul>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    persons: ['a'.'b'.'c'.'d']}})Copy the code

About the key

When Vue updates a list of elements rendered using V-for, it defaults to an “update in place” policy. If the order of data items is changed, Vue will not move DOM elements to match the order of data items, but simply reuse each element here:

<ul id="app">
  <li v-for="(person, index) in persons">
    {{ person }}
    <input type="text" />
    <button @click="handleClick(index)">Move down</button>
  </li>
</ul>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    persons: ['a'.'b'.'c'.'d']},methods: {
    handleClick (index) {
      const deleteItem = this.persons.splice(index, 1);
      this.persons.splice(index + 1.0. deleteItem); }}})Copy the code

In the “reuse in place” strategy, when the button is clicked, the input field does not move down with the text because the input field is not bound to the data, so vuejs uses the rendered DOM by default, whereas the text is bound to the data, so the text is re-rendered. This approach is the default list rendering strategy in VUE because it is efficient.

This default mode is effective, but at more of time, we don’t need to deal with this, so, in order to give the Vue a prompt, so that it can track the status of each node, thus reuse and reordering existing elements, we need to provide a unique key characteristics for each item, the Vue will rearrange the elements based on the key changes, It also removes elements where the key does not exist.

How to use key

Expected value: number | string with the same parent child element must have a unique key, repeat the key causes rendering errors, the key should be the only.

<ul id="app">
  <li v-for="(person, index) in persons" :key="person">
    {{ person }}
  </li>
</ul>
Copy the code
const vm = new Vue({
  el: '#app'.data: {
    persons: ['very'.'thought,'.'brother'.'Ming']}})Copy the code

It is not recommended to use the array index as the key, for example:

<li v-for="(person, index) in persons" :key="index">
  {{ person }}
</li>
Copy the code

When the array is changed, the page is re-rendered and Vue decides whether to move the element based on the key value. For example, when the page is re-rendered, the element with key “Shanshan” is

  • Shanshan
  • , and before the page is re-rendered, the element with key “Shanshan” is

  • Shanshan
  • , then Vue moves the Li element instead of re-creating an element. When the index of an array is used as the key value, the element’s key value will be reassigned after the page is rendered. For example, before we reverse the array:

    The element The key value
    < li > shanshan < / li > 0
    < li > think, < / li > 1
    Brother < li > < / li > 2
    Xiao Ming < li > < / li > 3

    After the reverse:

    The element The key value
    Xiao Ming < li > < / li > 0
    Brother < li > < / li > 1
    < li > think, < / li > 2
    < li > shanshan < / li > 3

    Vue will compare elements that had the same key before and after rendering, and if it finds any changes, it will regenerate an element. If it is worth using the index as the key, then all elements will be regenerated.

    So how is key unique?

    When collaborating with the background, each piece of data returned has an ID value, which is unique and can be used as a key by ID.

    Key is not only owned by V-for, it forces the element to be replaced instead of reusing it:

    <ul id="app">
      <button @click="show = ! show">{{ show ? 'Show' : 'hide '}</button>
      <input type="text" v-if="show" key="a" />
      <input type="text" v-else key="b" />
    </ul>
    Copy the code
    const vm = new Vue({
      el: '#app'.data: {
        show: true}})Copy the code

    V-for and v-if are used together

    Never use v-if and V-for on the same element. When Vue processes instructions, V-for takes precedence over V-if, so this template:

    <ul>
      <li
        v-for="user in users"
        v-if="user.isActive"
        :key="user.id"
      >
        {{ user.name }}
      </li>
    </ul>
    Copy the code

    The following operation will be performed:

    this.users.map(function (user) {
      if (user.isActive) {
        return user.name
      }
    })
    Copy the code

    So even if we render elements for only a small number of users, we have to traverse the entire list every time we re-render, regardless of whether the active users have changed. Therefore, the following two scenarios can be handled as follows:

    1. To filter items in a list.
    <ul id="app">
      <li
        v-for="user in users"
        v-if="user.isActive"
        :key="user.id"
      >
        {{ user.name }}
      </li>
    </ul>
    Copy the code
    const vm = new Vue({
      el: '#app'.data: {
        users: [{name: 'a'.isActive: true.id: 1},
          { name: 'b'.isActive: false.id: 2},
          { name: 'ct'.isActive: false.id: 3},
          { name: 'd'.isActive: true.id: 4},]}})Copy the code

    You can update the above code to:

     <! Get a new array from the original array. Render the new array. 
    <ul>
      <li
        v-for="user in activeUsers"
        :key="user.id"
      >
        {{ user.name }}
      </li>
    </ul>
    Copy the code
    const vm = new Vue({
      el: '#app'.data: {
        users: [{name: 'a'.isActive: true.id: 1},
          { name: 'b'.isActive: false.id: 2},
          { name: 'c'.isActive: false.id: 3},
          { name: 'd'.isActive: true.id: 4},].activeUsers: []
      }
    })
    vm.activeUsers = vm.users.filter(user= > user.isActive);
    Copy the code

    This method is for demonstration only, after learning the calculated properties, you will use the calculated properties to do.

    1. To avoid rendering lists that should be hidden
    <ul>
      <li
        v-for="user in users"
        v-if="shouldShowUsers"
        :key="user.id"
      >
        {{ user.name }}
      </li>
    </ul>
    Copy the code
    const vm = new Vue({
      el: '#app'.data: {
        users: [{name: 'a'.isActive: true.id: 1},
          { name: 'b'.isActive: false.id: 2},
          { name: 'c'.isActive: false.id: 3},
          { name: 'd'.isActive: true.id: 4},].shouldShowUsers: false}})Copy the code

    The HTML section can be replaced with:

    <ul v-if="shouldShowUsers">
      <li
        v-for="user in users"
        :key="user.id"
      >
        {{ user.name }}
      </li>
    </ul>
    Copy the code

    By putting v-if on the outer element, we no longer check shouldShowUsers for every user in the list. Instead, we only check it once and don’t do v-for if shouldShowUsers is no.

    Exercise _ Imitation Taobao commodity screening

    CSS file Contact the blogger to obtain the file, the required data:

    goodsList: [
      {
        title: 'with'.typeList: ['all'.'knitwear'.'Woolen coat'.'T shirt'.'Down jacket'.'cotton-padded clothes'.'who the clothes'.'trench coat'].id: 1}, {title: 'trousers'.typeList: ['all'.'Jeans'.'Little Feet/Pencil Pants'.'Casual pants' ,'Leggings'.'Harlan pants'].id: 2}, {title: 'skirt'.typeList: ['all'.'Dress'.'Skirt'.'Long Sleeve dress'.'Medium length Dress'].id: 3,}]Copy the code

    Practice _todoList

    Contact the blogger for exercise files ~

    The last

    If it is helpful to you, I hope I can give 👍 comment collection three even!

    Bloggers are honest and answer questions for free ❤

    Welcome to discuss in the comments section, the excavation officials will draw 100 nuggets in the comments section after the end of the Excavation project activity, see the details of the lucky draw in the event article, friends to discuss!!