Home >Web Front-end >JS Tutorial >Vue.JS introductory tutorial list rendering

Vue.JS introductory tutorial list rendering

高洛峰
高洛峰Original
2016-12-03 10:30:151351browse

You can use the v-repeat directive to render a list based on an array of objects on a ViewModel. For each object in the array, this directive will create a child Vue instance with that object as its $data object. These child instances inherit the data scope of the parent instance, so within repeated template elements you can access properties of the child instance as well as those of the parent instance. In addition, you can also get the array index corresponding to the current instance through the $index property.

<ul id="demo">
 <li v-repeat="items" class="item-{{$index}}">
 {{$index}} - {{parentMsg}} {{childMsg}}
 </li>
</ul>
var demo = new Vue({
 el: &#39;#demo&#39;,
 data: {
 parentMsg: &#39;Hello&#39;,
 items: [
  { childMsg: &#39;Foo&#39; },
  { childMsg: &#39;Bar&#39; }
 ]
 }
})

Check the effect, it should be easy to get the result

Block-level repetition

Sometimes we may need to repeat a block containing multiple nodes. In this case, we can use the d477f9ce7bf77f53fbcf36bec1b69b7a tag to wrap this block. The d477f9ce7bf77f53fbcf36bec1b69b7a tag here only plays a semantic wrapping role and will not be rendered by itself. For example:

<ul>
 <template v-repeat="list">
 <li>{{msg}}</li>
 <li class="divider"></li>
 </template>
</ul>

Simple value array

Simple value (primitive value) is a string, number, boolean, etc. that is not an object. For arrays containing simple values, you can use $value to access the value directly:

<ul id="tags">
 <li v-repeat="tags">
 {{$value}}
 </li>
</ul>

new Vue({
 el: &#39;#tags&#39;,
 data: {
 tags: [&#39;JavaScript&#39;, &#39;MVVM&#39;, &#39;Vue.js&#39;]
 }
})

Using aliases
Sometimes we may want to more explicitly access a variable in the current scope rather than implicitly falling back to parent scope. You can do this by providing an argument to the v-repeat directive and using it as an alias for the item to be iterated over: Including push(), pop(), shift(), unshift(), splice(), sort() and reverse()) are intercepted, so calling these methods will also automatically trigger a view update.

<ul id="users">
 <li v-repeat="user : users">
  {{user.name}} - {{user.email}}
 </li>
</ul>


The following is a demonstration example, the data item will be removed when the button is clicked

var users = new Vue({
 el: &#39;#users&#39;,
 data: {
  users: [
   { name: &#39;Foo Bar&#39;, email: &#39;foo@bar.com&#39; },
   { name: &#39;John Doh&#39;, email: &#39;john@doh.com&#39; }
  ]
 }
});


Extension method

Vue.js adds two convenient methods to the observed array: $set () and $remove().

You should avoid setting elements in data-bound arrays directly by index, such as demo.items[0] = {}, because these changes cannot be detected by Vue.js. You should use the extended $set() method:

// 以下操作会触发 DOM 更新
demo.items.unshift({ childMsg: &#39;Baz&#39; })
demo.items.pop()

$remove() is just syntactic sugar for the splice() method. It will remove the element at the given index. When the argument is not a numeric value, $remove() searches the array for the value and removes the first corresponding element found.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
</head>
<body>
 <ul id="tags">
  <li v-repeat="tags">
   {{$value}}
  </li>
 </ul>
 
 <input type="button" value="测试" onclick="myClick();">
<script>
 var tag = new Vue({
  el: &#39;#tags&#39;,
  data: {
   tags: [&#39;标签一&#39;, &#39;标签二&#39;, &#39;标签三&#39;]
  }
 });
 
 function myClick(){
  tag.tags.pop();
 }
</script>
</body>
</html>



// 不要用 `demo.items[0] = ...`
demo.items.$set(0, { childMsg: &#39;Changed!&#39;})

Replace Array

When you use non-mutating methods, such as filter(), concat() or slice(), the returned array will be a different instance. In this case, you can replace the old array with the new one:

// 删除索引为 0 的元素。
demo.items.$remove(0)


You might think that this will cause the entire list's DOM to be destroyed and re-rendered. But don't worry, Vue.js can recognize whether an array element has an associated Vue instance and reuse it as efficiently as possible.

Use track-by (track-by attribute in vue)

In some cases, you may need to replace the array with a completely new object (such as the object returned by the API call). If each of your data objects has a unique id attribute, then you can use the track-by attribute parameter to give Vue.js a hint so that it can reuse existing Vue instances and DOM nodes with the same id.
For example: your data looks like this

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
</head>
<body>
 <ul id="tags">
  <li v-repeat="tags">
   {{$value}}
  </li>
 </ul>
 
 <input type="button" value="测试" onclick="myClick();">
<script>
 var tag = new Vue({
  el: &#39;#tags&#39;,
  data: {
   tags: [&#39;标签一&#39;, &#39;标签二&#39;, &#39;标签三&#39;]
  }
 });
 
 function myClick(){
  //tag.tags.pop();
  //tag.tags[0] = &#39;修改后的内容不生效&#39;;
  tag.tags.$set(0, &#39;修改后的内容生效&#39;);
  tag.tags.$remove(1);
 }
</script>
</body>
</html>

Then you can give a prompt like this:

demo.items = demo.items.filter(function (item) {
 return item.childMsg.match(/Hello/)
})



When replacing the items array, if Vue.js encounters a _uid: '88f869d', it will know that it can directly reuse existing instances with the same _uid. Proper use of track-by can greatly improve performance when re-rendering large v-repeat lists with fresh data.

Traverse objects

You can also use v-repeat to traverse all properties of an object. Each duplicate instance will have a special attribute $key. For simple values, you can also use the $value property just like accessing simple values ​​in an array.

{
 items: [
 { _uid: &#39;88f869d&#39;, ... },
 { _uid: &#39;7496c10&#39;, ... }
 ]
}

<div v-repeat="items" track-by="_uid">
 <!-- content -->
</div>

In ECMAScript 5, there is no mechanism to detect when a new property is added to an object or a property is removed from an object. To address this problem, three extension methods will be added to the observed object in Vue.js: $add(key, value), $set(key, value) and $delete(key). These methods can be used to trigger corresponding view updates when properties of the observed object are added/removed. The difference between the methods $add and $set is that $add will return early when the specified key already exists in the object, so calling obj.$add(key) will not overwrite the existing value with undefined.


Iteration range

v-repeat can also accept an integer. In this case it will display a template multiple times. The example below will iterate 3 times.

<ul id="repeat-object">
 <li v-repeat="primitiveValues">{{$key}} : {{$value}}</li>
 <li>===</li>
 <li v-repeat="objectValues">{{$key}} : {{msg}}</li>
</ul>

new Vue({
 el: &#39;#repeat-object&#39;,
 data: {
  primitiveValues: {
   FirstName: &#39;John&#39;,
   LastName: &#39;Doe&#39;,
   Age: 30
  },
  objectValues: {
   one: {
    msg: &#39;Hello&#39;
   },
   two: {
    msg: &#39;Bye&#39;
   }
  }
 }
});

Array Filter

Sometimes we just need to display a filtered or sorted version of an array without actually changing or resetting the original data. Vue provides two built-in filters to simplify such needs: filterBy and orderBy.

<div id="range">
 <div v-repeat="val">Hi! {{$index}}</div>
</div>

The above is the entire content of this article, I hope it will be helpful to everyone’s study


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn