List Rendering for Learning Vue Together

In the development of Vue, list data binding is very simple and easy to use. In this paper, through some simple small examples, the use of v-for is described, which is only for learning to share. If there are any deficiencies, please also correct them.

Correspond an array to a set of elements using v-for

We can use the v-for directive to render a list based on an array.The v-for Directive requires special syntax in the form of item in items, where items is the source data array and item is the alias of the array element being iterated.As follows:

1 <ul>
2     <li v-for="fruit in fruits">
3         {{ fruit.name }}
4     </li>
5 </ul>

In the v-for block, we can access the properties of all parent scopes.v-for also supports an optional second parameter, the index of the current item.As follows:

1 <ul>
2     <li v-for="(fruit, index) in fruits">
3         {{ msg }} - {{ index }} - {{ fruit.name }}
4     </li>
5 </ul>

You can also use ofInstead of in as a separator because it is closer to the JavaScript iterator syntax, as follows:

1 <ul id="example-3">
2     <li v-for="fruit of fruits">
3         {{ fruit.name }}
4     </li>
5 </ul>

Where fruits is an array defined in js as follows:

 1 <script type="text/javascript">
 2     var app = new Vue({
 3         el: '#app',
 4         data: {
 5             msg: 'hello world!!!',
 6             fruits: [
 7                 {id:0, name: 'Apple' },
 8                 {id:1, name: 'Pear' },
 9                 {id:2, name: 'Orange'},
10                 {id:3, name:'Banana'}
11             ]
12         }
13     });
14 </script>

Use objects in v-for

In addition to traversing arrays, V-for can also traverse the properties of an object using v-for, as follows:

1 <ul>
2     <li v-for="v in book">
3         {{ v }}
4     </li>
5 </ul>

You can also provide a second parameter, the property name (that is, the key name), as follows:v,n for value and name

1 <ul>
2     <li v-for="(v,n) in book">
3         {{n}}--{{ v }}
4     </li>
5 </ul>

You can also use the third parameter as an index:, i represents the current index, as follows:

1 <ul>
2     <li v-for="(v,n,i) in book">
3         {{n}}--{{ v }}---{{i}}
4     </li>
5 </ul>

In summary:

  1. For arrays, the first parameter is content and the second parameter is index;
  2. For objects, the first parameter is the value, the second parameter is the name, and the third parameter is the index.

Note: When traversing an object, the result of Object.keys() is traversed, but its result is not guaranteed to be consistent across different JavaScript engines.

Where book is an object, as follows:

 1 <script type="text/javascript">
 2     var app = new Vue({
 3         el: '#app',
 4         data: {
 5             msg: 'hello world!!!',
 6             book: {
 7                 title: 'How to do lists in Vue',
 8                 author: 'Jane Doe',
 9                 publishedAt: '2016-04-10'
10         }
11     });
12 </script>

Maintenance Status

When Vue is updating the list of elements rendered with v-for, it defaults to the in-place update 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 will update each element in place and ensure that they are rendered correctly at each index location.This default mode is efficient, but only applies to list rendering output that does not depend on subcomponent state or temporary DOM state (for example, form input values).To give Vue a hint so that it can track the identity of each node, thereby reusing and reordering existing elements, you need to provide a unique key attribute for each item, as follows:

1 <div v-for="(f,i) in fruits" v-bind:key="f.id">
2     <!-- content -->
3     {{f.name}}-----{{i}}
4 </div>

It is recommended that you provide key attribute s when using V-for whenever possible, unless traversing the DOM content of the output is simple or you deliberately rely on default behavior for performance improvements.Because it is a common mechanism for Vue to identify nodes, key is not only specifically associated with v-for.Do not use non-basic type values, such as objects or arrays, as keys for v-for. Use values of string or numeric type.

Array Update Detection

Vue will be wrapped around the mutant methods of the listened array, so they will also trigger view updates.These wrapped methods include:
push(),pop(),shift(),unshift(),splice(),sort(),reverse()

You can open the console and try calling the mutation method on the items array of the previous example.As follows:

Replace Array

Variant methods, as the name implies, change the original array in which they are called.In contrast, there are non-mutating methods, such as filter(), concat(), and slice().They do not change the original array, but always return a new one.When using a nonvariant method, you can replace the old array with a new one:

1 app.items = app.items.filter(function (item) {
2   return item.message.match(/Foo/)
3 })

You may think this will cause Vue to discard the existing DOM and re-render the entire list.Fortunately, this is not the case.Vue implements intelligent heuristic methods to maximize the reuse of DOM elements, so replacing the original array with an array containing the same elements is a very efficient operation.

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

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

Notes on Object Change Detection

Due to JavaScript limitations, Vue cannot detect the addition or deletion of object properties as follows:

1 vm.items[1] = 'x' // Not responsive
2 vm.items.length = 2 // Not responsive

To solve the first type of problem, the following two approaches can be implemented:

1 // Vue.set
2 Vue.set(vm.items, indexOfItem, newValue)
3 // Array.prototype.splice
4 vm.items.splice(indexOfItem, 1, newValue)
5 //You can also use vm.$set Instance method, which is global Vue.set An alias:
6 vm.$set(vm.items, indexOfItem, newValue)
 1 // `vm.a` is now responsive
 2 vm.b = 2
 3 // `vm.b` is not responsive
 4 //For instances already created, Vue does not allow dynamic addition of root-level responsive attributes.
 5 //However, you can use the Vue.set(object, propertyName, value) method to add responsive attributes to nested objects.For example, for:
 6 //You can add a new age attribute to the nested userProfile object:
 7 //Vue.set(vm.userProfile, 'age', 27)
 8 //You can also use the vm.$set instance method, which is just an alias for the global Vue.set:
 9 //vm.$set(vm.userProfile, 'age', 27)
10 //Sometimes you may need to assign several new attributes to an existing object, such as using Object.assign() or.extend().
11 //In this case, you should create a new object with the properties of two objects.So if you want to add new responsive attributes, don't look like this:
12 Object.assign(vm.userProfile, {
13     age: 27,
14      favoriteColor: 'Vue Green'
15 });
16 //You should do this:
17 vm.userProfile = Object.assign({}, vm.userProfile, {
18     age: 27,
19     favoriteColor: 'Vue Green'
20 });

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

1 vm.items.splice(newLength)

Show filtered/sorted results

Sometimes we want to show a filtered or sorted version of an array without actually changing or resetting the original data.In this case, you can create a computed property to return a filtered or sorted array.

1 <ul>
2     <li v-for="n in evenNumbers">{{ n }}</li>
3 </ul>

In cases where computational attributes are not applicable (for example, in a nested v-for loop), you can use one method:

1  <ul>
2     <li v-for="n in even(numbers)">{{ n }}</li>
3 </ul>

Where evenNumbers is a computed property and evens is a function, as follows:

 1 <script type="text/javascript">
 2     var app = new Vue({
 3         el: '#app',
 4         data: {
 5             msg: 'hello world!!!',
 6             numbers: [ 1, 2, 3, 4, 5 ],        
 7         },
 8         methods: {    
 9             even: function (numbers) {
10                 return numbers.filter(function (number) {
11                     return number % 2 === 0;
12                 })
13             }
14         },
15         computed: {
16             evenNumbers: function () {
17                 return this.numbers.filter(function (number) {
18                     return number % 2 === 0;
19                 })
20             }
21         }
22 });
23 </script>
24                             

Use value range in v-for

v-for can also accept integers.In this case, it will repeat the template the number of times.

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

Use v-for on <template>

Similar to v-if, you can use <template> with v-for to cycle through a section of content that contains multiple elements.For example:

1 <ul>
2     <template v-for="f in fruits">
3         <li>{{ f.name }}</li>
4         <li class="divider" role="presentation"></li>
5     </template>
6 </ul>

Remarks

The Middle Wall of Unol Shubo Mountain Road

Xin Qi Ji

A young man loves upstairs without feeling sad.Love upstairs, and say sorry for new words.

Now knowledge is full of melancholy and taste, but I want to say it again.To say it's still resting, but it's still cool all autumn.

Tags: Javascript Vue Attribute

Posted on Tue, 14 Jan 2020 08:22:39 -0800 by robbyc