Vue.js (v) List rendering v-for

Source: Internet
Author: User
Tags unique id

V-for= "Item in Items"//array update detection//object Change detection considerations//Display Filter/Sort results//v-for of a range of values//

V-for
  • Array: We use the v-for instruction to render based on a list of options for a set of arrays. The V-FOR directive needs to use the special syntax of item in items, where items are an array of source data and item is an alias for the iteration of an array element.
    <ul id="example-1"> <li V for="Item in Items">{{Item.message}}</li></ul>varExample1 =NewVue ({el:'#example-1', data: {items: [{message:'Foo'}, {message:'Bar' }        ]    }})==>· Foo Bar

    In the v-for block, we have full access to the parent scope property. V-for also supports an optional second parameter that is the index of the current item

    <ul id="example-2"> <li V for="(item, index) in items">{{Parentmessage}}-{{Index}}-{{Item.message}}</li></ul>varExample2 =NewVue ({el:'#example-2', data: {parentmessage:'Parent', items: [{message:'Foo'}, {message:'Bar'}]}) You can also substitute forinchas a delimiter, because it is closest to the syntax of a JavaScript iterator:<div V- for="Item of items"></div>

  • Object: WithV-for iterate through the properties of an object
    <ul> <li V for="value in Object">{{value}}</li></ul>varApp =NewVue ({el:"#app", data:{Object: {tit:"title", Con:"content", Time:"Noon"        }    }})==>• Title • Content

    You can provide the second parameter as a key name

    <ul>    <li vfor ="(Value,key) in Object">        {{key}}: {{ Value}}    </li></ul>==>tit: Title con: Content Time: Noon

    The third argument is an index

    <ul>    <li vfor ="(Value,key) in Object">        {{ Index}}. : {{Key}}: {{    value}} </li></ul>==>· 0 . Tit: Title · 1 . Con: Content · 2. Time: Noon

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

  • Key:when vue.js is updating a rendered list of elements with v-for, it defaults to the "in-place reuse" policy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but rather simply reuse each element here and make sure that it shows each element that has been rendered under a specific index. This is similar to the Vue 1.x track-by= "$index". This default mode is efficient, but only applies to list rendered output that does not rely on subcomponent state or temporary DOM state (for example, form input values). To give Vue a hint so that it can track the identities of each node, reusing and reordering existing elements, you need to provide a unique key property for each item. The ideal key value is a unique ID for each item. This particular property is equivalent to the track-by of Vue 1.x, but it works like a property, so you need to use V-bind to bind the dynamic value (use shorthand here):
    <div vfor ="item in Items" : key="item.id">    <!--content--></div>
    It is recommended to provide the key whenever possible when using v-for, unless traversing the output DOM content is straightforward, or deliberately relying on the default behavior for performance gains. because it is a common mechanism for the Vue recognition node, key is not specifically associated with v-for, and Key has other uses, and we will see other uses in the guide later.

Array update detection
    • Variation Method : Vue contains a set of variation methods for observing arrays, so they will also trigger view updates. These methods are as follows:
      * push ()* pop ()* shift() * unshift () * Splice () * sort ()* Reverse ( )
      Above example : App.object.push ({message: ' Baz '}) will be added at the end of the list Baz

    • array Substitution : Variant methods (mutation method), as the name implies, change the original array that is called by these methods. In contrast, there are non-mutation (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 a non-mutating method, you can replace the old array with a new array:
      Example1.items = Example1.items.filter (function (item) {    return item.message.match (/foo/) })

      You might think that this will cause Vue to discard the existing DOM and render the entire list again. Fortunately, that's not the case. Vue implements some intelligent, heuristic methods for maximizing the reuse of DOM elements, so it is very efficient to use an array with the same elements to replace the original array.

  • PrecautionsBecause of JavaScript limitations, Vue cannot detect an array of the following changes:
      1. When you use an index to set an item directly, for example: vm.items[indexofitem] = newvalue
      2. When you modify the length of an array, for example: Vm.items.length = Newlength
    As an example:
    var New Vue ({    data: {        items: ['a'b']  c']    }}) vm.items[1'x' // not responsive. 2 // not responsive.

    In order to solve the first kind of problem, the following two ways can achieve and vm.items[indexofitem] = newvalue the same effect, but also trigger the status update:

    // Vue.set Vue. Set (Vm.items, Indexofitem, NewValue) // Array.prototype.splice 1, NewValue)

    You can also use VMS. $set instance method, which is an alias of the global method Vue.set

    vm.$Set(Vm.items, Indexofitem, NewValue)

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

    Vm.items.splice (Newlength)

Object Change Detection considerations
  • or because of JavaScript limitations, Vue cannot detect the addition or deletion of object properties:
    var New Vue ({    data: {        1    }})//  ' VM.A ' is now responsive  2 // ' vm.b ' is not responsive

  • Vue cannot dynamically add a root-level response property to an instance that has already been created. However, you can use the Vue.set (object, key, value) method to add a responsive property to a nested object. For example, for:
    var New Vue ({    data: {        userprofile: {            'anika'}}}    )

    You can add a new age property to the nested UserProfile object:

    Vue. Set '  Age ' )

    You can also use VMS. $set instance method, which is simply an alias for the global Vue.set:

    vm.$set'age')

    Sometimes you may need to give more than one new attribute to an existing object, such as using object.assign () or _.extend (). In this case, you should create a new object with a property of two objects. So, if you want to add a new responsive property, don't look like this:

    object.assign (vm.userprofile, {    ,    'Vue Green' ) })

    You should do this:

    Vm.userprofile = object.assign ({}, Vm.userprofile, {    ),    ' Vue Green ' })

Show Filter/Sort results
  • Sometimes we want to display a filtered or sorted copy of an array without actually altering or resetting the original data.
  • In this case,You can create a computed property that returns a filtered or sorted array. For example:
    <li vfor ="N in evennumbers">{{n}}</li>data: {    1  2345  ]},computed: {    evennumbers:function () {         return  This . Numbers.filter (function (number) {            return20        })    }}

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

    <li vfor ="N in even (numbers)">{{n}}</li>data: {      12345  ]},methods: {    even:function (numbers) {         return Numbers.filter (function (number) {            return20        })    } }

V-for of a range of values
  • v-for  can also take integers. In this case, it repeats multiple templates
     <div> <span v-for  = " n in  "  >{{n}} </span></div>==>1  2  3  4   5  6  7  8  9  10  

     

  • v-for on a <template> similar to v-if, you can also use <template> with v-for to render multiple elements. For example:
    <ul>    <template vfor ='item in Items'>        <li>{{ Item.msg}}</li>        class="divider"></li>    </template></ul>

    • V-for with V-if
      <ul vIf="todos.length">    <li vfor ="  Todo in Todos">        {{todo}}    </li></ul><p vElse >no Todos left!</p>

-------End-------

Vue.js (v) List rendering v-for

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.