Home >Web Front-end >JS Tutorial >Detailed introduction to list rendering in vuejs

Detailed introduction to list rendering in vuejs

不言
不言Original
2018-08-14 16:47:382827browse

This article brings you a detailed introduction to list rendering in vuejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use v-for to correspond an array to a set of elements

We use the v-for instruction to render based on the option list of a set of arrays. The v-for directive requires special syntax of the form item in items, where items is the source data array and item is an alias for iterating over the array elements.

<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
var example1 = new Vue({
el: &#39;#example-1&#39;,
data: {
items: [
{ message: &#39;Foo&#39; },
{ message: &#39;Bar&#39; }
]
}
})

In the v-for block, we have full access to the parent scope properties. 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>
var example2 = new Vue({
el: &#39;#example-2&#39;,
data: {
parentMessage: &#39;Parent&#39;,
items: [
{ message: &#39;Foo&#39; },
{ message: &#39;Bar&#39; }
]
}
})

You can also use of instead of in as the separator, because it is the syntax closest to javascript iterators

<p v-for="item of items"></p>

v-for for an object

You can also use v-for to iterate through the properties of an object.

<ul id="v-for-object" class="demo">
<li v-for="value in object">
{{ value }}
</li>
</ul>
new Vue({
el: &#39;#v-for-object&#39;,
data: {
object: {
firstName: &#39;John&#39;,
lastName: &#39;Doe&#39;,
age: 30
}
}
})

You can also provide the second parameter as the key name

<p v-for="(value, key) in object">
{{ key }}: {{ value }}
</p>

The third parameter is the index:

<p v-for="(value, key, index) in object">
{{ index }}. {{ key }}: {{ value }}
</p>

When traversing the object, it is Traverse according to the results of Object.key(), but there is no guarantee that its results are consistent under different javascript engines.

key

When vue.js is being updated using v-for When rendering a list of elements, it defaults to the "in-place reuse" strategy. If the order of data items is changed. Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element there and make sure it displays each element rendered at a specific index. This is similar to track-by="$index" of vue1.x.

This default mode is efficient, but is only suitable for list rendering output that does not rely on subcomponent state or temporary DOM state (for example: form input values).

In order to give Vue a hint so that it can track the identity of each node and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. The ideal key value is a unique id for each item. This special attribute is equivalent to vue1.x's track-by, but it works like a property, so you need to use v-bind to bind dynamically value.

<p v-for="item in items" :key="item.id">
<!-- 内容 -->
</p>

It is recommended to provide key when using v-for as much as possible, unless traversing the output dom content is very simple or can be relied on Default behavior to gain performance improvements.

Because it is a general mechanism for Vue to identify nodes, key is not specifically related to v-for, key also has other uses,

Array update detection

Compiled methods

#vue contains compiled methods that always observe the array, so they will also trigger view updates.

* push()————Into the array

* pop()———— Out of the array

* shift()————

* unshift()

* splice()——Split the array

* sort() ————Sort the array

* reverse()————Flip the array

Replace the array

mutation method, which will change the original array called by these methods. In contrast, there are also non-mutational methods. For example: filter(), concat() and slice().

These do not change the original array, but always return a new array. When using the non-mutation method, you can replace the old array with a new array

##

example1.items = example1.items.filter(function (item) {
return item.message.match(/Foo/)
})

You may think that this will cause vue to discard the existing dom and re-renders the entire list. Fortunately, this is not the case. Vue has implemented some smart and heuristic methods in order to maximize the reuse of DOM elements, so replacing the original array with an array containing the same elements is a very efficient operation.

Notes

Due to JavaScript limitations, vue cannot detect the following changed arrays

1. When you use an index to directly set an item, for example: vm.items[ indexOfItem] = newValue

2. When you modify the length of the array, for example: vm.items.length = newLength

var vm = new Vue({
data: {
items: [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
}
})
vm.items[1] = &#39;x&#39; // 不是响应性的
vm.items.length = 2 // 不是响应性的

In order to solve the first type of problem, the following two methods can achieve the same effect as vm.items[indexOfItem] = newValue, and will also trigger status update

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

你也可以使用vm.$set实例方法,该方法是全局方法vue.set的一个别名

vm.$set(vm.items, indexOfItem, newValue)

为了解决第二类问题,你可以使用splice

vm.items.splice(newLength)

splice()方法向/从数组添加/删除项目,然后返回被删除的项目

arrayObject.splice(index,howmany,item1,.....,itemX)

index

必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。

howmany

必需。要删除的项目数量。如果设置为 0,则不会删除项目。

item1, ..., itemX

可选。向数组添加的新项目。

对象更改检测注意事项

还是由于javascript的限制,vue不能检测对象属性的添加或删除

var vm = new Vue({
data: {
a: 1
}
})
// `vm.a` 现在是响应式的
 
vm.b = 2
// `vm.b` 不是响应式

对于已经创建的实例,vue不能动态添加跟级别的响应式属性。但是,可以使用 Vue.set(object, key, value)方法向嵌套对象添加响应式属性。

var vm = new Vue({
data: {
userProfile: {
name: &#39;Anika&#39;
}
}
})

你可以添加一个age属性到嵌套的userProfile对象:

Vue.set(vm.userProfile, &#39;age&#39;, 27)

你还可以使用vm.$set实例方法,他只是全局vue.set的别名

vm.$set(vm.userProfile, &#39;age&#39;, 27)

有事你可能需要为已有对象赋予多个新属性,比如使用 Object.assign() 或 _.extend()。在这种情况下,你应该用两个对象的属性创建一个新的对象。所以,如果你想添加新的响应式属性,不要像这样:

Object.assign(vm.userProfile, {
age: 27,
favoriteColor: &#39;Vue Green&#39;
})
你应该这样:
vm.userProfile = Object.assign({}, vm.userProfile, {
age: 27,
favoriteColor: &#39;Vue Green&#39;
})

显示过滤/排序结果

有事,我们想要显示一个数组的过滤或排序副本,而不实际改变 或重置原始数据。在这种情况下,可以创建返回过滤或排序 数组的计算属性。

<li v-for="n in evenNumbers">{{ n }}</li>
data: {
  numbers: [ 1, 2, 3, 4, 5 ]
},
computed: {
  evenNumbers: function () {
    return this.numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}

在计算属性不使用的情况下,(例如,在嵌套v-for循环中)你可以使用method方法。

data: {
numbers: [ 1, 2, 3, 4, 5 ]
},
methods: {
even: function (numbers) {
return numbers.filter(function (number) {
return number % 2 === 0
})
}
}

一段取值范围的v-for

v-for也可以取整数。在这种情况下 ,它将重复多刺激模板。

<p>
<span v-for="n in 10">{{ n }} </span>
</p>

v-for on a d477f9ce7bf77f53fbcf36bec1b69b7a

类似于v-if,你也可以利用带有v-for的d477f9ce7bf77f53fbcf36bec1b69b7a渲染多个元素。

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

v-for with v-if

当他们处于同一节点,v-for的优先级比v-if更高,这意味着v-if将分别重复运行与每个v-for循环中。当你想为仅有的一些项渲染节点时,这种优先级的机制会十分有用。

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

上面的代码只传递了未完成的 todos。

而如果你的目的是有条件地跳过循环的执行,那么可以将 v-if 置于外层元素 (或 d477f9ce7bf77f53fbcf36bec1b69b7a)上。如:

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

一个组件的v-for

了解组件相关知识,查看组件。完全可以先跳过他,以后再回来 查看。

在自定义组件里,你可以像任何普通元素一样用v-for.

<my-component v-for="item in items" :key="item.id"></my-component>

当在组件中使用 v-for 时,key 现在是必须的。

然而,任何数据都不会被自动传递到组件里,因为组件有自己独立的作用域。为了把迭代数据传递到组件里。

我们要用props:

<my-component
v-for="(item, index) in items"
v-bind:item="item"
v-bind:index="index"
v-bind:key="item.id"
></my-component>

不自动将item注入到组件里的原因是,这会使得组件与v-for的运作紧密耦合。明确组件数据的来源能够使组件在其他场合重复使用。

<p id="todo-list-example">
<form v-on:submit.prevent="addNewTodo">
<label for="new-todo">Add a todo</label>
<input
v-model="newTodoText"
id="new-todo"
placeholder="E.g. Feed the cat"
>
<button>Add</button>
</form>
<ul>
<li
is="todo-item"
v-for="(todo, index) in todos"
v-bind:key="todo.id"
v-bind:title="todo.title"
v-on:remove="todos.splice(index, 1)"
></li>
</ul>
</p>

注意这里的is="todo-item"属性。这种做法在使用dom模板时是十分必要的。因为在ff6d136ddc5fdfeffaf53ff6ee95f185元素内只有25edfb22a4f469ecb59f1190150159c6元素 会被看做有效内容。这样做实现的效果与c20b531f5b99ef8837ce29ced08ba7cd相同。但是可以避开一些潜在的浏览器解析错误。

<p id="todo-list-example">
  <form v-on:submit.prevent="addNewTodo">
    <label for="new-todo">Add a todo</label>
    <input
      v-model="newTodoText"
      id="new-todo"
      placeholder="E.g. Feed the cat"
    >
    <button>Add</button>
  </form>
  <ul>
    <li
      is="todo-item"
      v-for="(todo, index) in todos"
      v-bind:key="todo.id"
      v-bind:title="todo.title"
      v-on:remove="todos.splice(index, 1)"
    ></li>
  </ul>
</p>

注意这里的 is="todo-item" 属性。这种做法在使用 DOM 模板时是十分必要的,因为在 ff6d136ddc5fdfeffaf53ff6ee95f185 元素内只有 25edfb22a4f469ecb59f1190150159c6 元素会被看作有效内容。这样做实现的效果与 c20b531f5b99ef8837ce29ced08ba7cd 相同,但是可以避开一些潜在的浏览器解析错误。查看 DOM 模板解析说明 来了解更多信息。

Vue.component(&#39;todo-item&#39;, {
  template: &#39;\
    <li>\
      {{ title }}\
      <button v-on:click="$emit(\&#39;remove\&#39;)">Remove</button>\
    </li>\
  &#39;,
  props: [&#39;title&#39;]
})
 
new Vue({
  el: &#39;#todo-list-example&#39;,
  data: {
    newTodoText: &#39;&#39;,
    todos: [
      {
        id: 1,
        title: &#39;Do the dishes&#39;,
      },
      {
        id: 2,
        title: &#39;Take out the trash&#39;,
      },
      {
        id: 3,
        title: &#39;Mow the lawn&#39;
      }
    ],
    nextTodoId: 4
  },
  methods: {
    addNewTodo: function () {
      this.todos.push({
        id: this.nextTodoId++,
        title: this.newTodoText
      })
      this.newTodoText = &#39;&#39;
    }
  }
})

相关推荐:

js实现页面间数据传递的代码

reac如何t实现更换皮肤颜色的功能

 jQuery中的方法有哪些?jQuery中常用的方法(附代码)

The above is the detailed content of Detailed introduction to list rendering in vuejs. For more information, please follow other related articles on the PHP Chinese website!

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