vue数据调取怎么渲染列表_Vue 列表渲染 · Vue.js教程

v-for

我们用 v-for 指令根据一组数组的选项列表进行渲染。 v-for 指令需要以 item in items 形式的特殊语法, items 是源数据数组并且 item 是数组元素迭代的别名。

基本用法

  • {{ item.message }}

var example1 = new Vue({

el: '#example-1',

data: {

items: [

{message: 'foo' },

{message: 'Bar' }

]

}

})

结果:

{{item.message}}

在 v-for 块中,我们拥有对父作用域属性的完全访问权限。 v-for 还支持一个可选的第二个参数为当前项的索引。

  • {{ parentMessage }} - {{ index }} - {{ item.message }}

var example2 = new Vue({

el: '#example-2',

data: {

parentMessage: 'Parent',

items: [

{ message: 'Foo' },

{ message: 'Bar' }

]

}

})

结果:

{{ parentMessage }} - {{ index }} - {{ item.message }}

你也可以用 of 替代 in 作为分隔符,因为它是最接近 JavaScript 迭代器的语法:

Template v-for

如同 v-if 模板,你也可以用带有 v-for 的 标签来渲染多个元素块。例如:

  • {{ item.msg }}

对象迭代 v-for

你也可以用 v-for 通过一个对象的属性来迭代。

  • {{ value }}

new Vue({

el: '#repeat-object',

data: {

object: {

FirstName: 'John',

LastName: 'Doe',

Age: 30

}

}

})

结果:

{{ value }}

你也可以提供第二个的参数为键名:

{{ key }} : {{ value }}

第三个参数为索引:

{{ index }}. {{ key }} : {{ value }}

在遍历对象时,是按 Object.keys() 的结果遍历,但是不能保证它的结果在不同的 JavaScript 引擎下是一致的。

整数迭代 v-for

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

{{ n }}

结果:

{{ n }}

组件 和 v-for

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

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

然而他不能自动传递数据到组件里,因为组件有自己独立的作用域。为了传递迭代数据到组件里,我们要用 props :

v-for="(item, index) in items"

v-bind:item="item"

v-bind:index="index">

不自动注入 item 到组件里的原因是,因为这使得组件会紧密耦合到 v-for 如何运作。在一些情况下,明确数据的来源可以使组件可重用。

下面是一个简单的 todo list 完整的例子:

v-model="newTodoText"

v-on:keyup.enter="addNewTodo"

placeholder="Add a todo"

>

  • is="todo-item"

    v-for="(todo, index) in todos"

    v-bind:title="todo"

    v-on:remove="todos.splice(index, 1)"

    >

Vue.component('todo-item', {

template: '\

\

{{ title }}\

X\

\

',

props: ['title']

})

new Vue({

el: '#todo-list-example',

data: {

newTodoText: '',

todos: [

'Do the dishes',

'Take out the trash',

'Mow the lawn'

]

},

methods: {

addNewTodo: function (){

this.todos.push(this.newTodoText)

this.newTodoText = ''

}

}

})

is="todo-item"

v-for="(todo, index) in todos"

v-bind:title="todo"

v-on:remove="todos.splice(index, 1)"

>


版权声明:本文为weixin_36025176原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。