1.v-if
模板文件中
<!-- Handlebars template -->
{{#if ok}}
<h1>Yes</h1>
{{/if}}
vue中
<h1 v-if="ok">Yes</h1>
//添加else
<h1 v-if="ok">Yes</h1>
<h1 v-else>No</h1>
//template v-if
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
2.v-show
<h1 v-show="ok">Hello!</h1>
v-if 回创建和销毁对象,而v-show只是调用css的属性
3.v-for
(1)基本
<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
(2)可选的第二个参数
<ul id="example-2">
<li v-for="(item, index) in items">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>
var example2 = new Vue({
el: '#example-2',
data: {
parentMessage: 'Parent',
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
(3)也可以用of语法
<div v-for="item of items"></div>
(4)<template>和for
<ul>
<template v-for="item in items">
<li>{{ item.msg }}</li>
<li class="divider"></li>
</template>
</ul>
(5)object v-for
会遍历所有的对象属性
<ul id="repeat-object" class="demo">
<li v-for="value in object">
{{ value }}
</li>
</ul>
new Vue({
el: '#repeat-object',
data: {
object: {
FirstName: 'John',
LastName: 'Doe',
Age: 30
}
}
})
也可以提供第二个参数
<div v-for="(value, key) in object">
{{ key }} : {{ value }}
</div>
<div v-for="(value, key, index) in object">
{{ index }}. {{ key }} : {{ value }}
</div>
(6)range v-for
<div>
<span v-for="n in 10">{{ n }}</span>
</div>
(7) Components
<my-component v-for="item in items"></my-component>
注意:因为组件有自己的作用域所以必须绑定参数才能传参
<my-component
v-for="(item, index) in items"
v-bind:item="item"
v-bind:index="index">
</my-component>
代码示例
<div id="todo-list-example">
<input
v-model="newTodoText"
v-on:keyup.enter="addNewTodo"
placeholder="Add a todo"
>
<ul>
<li
is="todo-item"
v-for="(todo, index) in todos"
v-bind:title="todo"
v-on:remove="todos.splice(index, 1)"
></li>
</ul>
</div>
Vue.component('todo-item', {
template: '\
<li>\
{{ title }}\
<button v-on:click="$emit(\'remove\')">X</button>\
</li>\
',
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 = ''
}
}
})
(8)顺序 :key
<div v-for="item in items" :key="item.id">
<!-- content -->
</div>
注意
受限于JavaScript以下方法可以检测数组的变化
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
下面这些不可以
vm.items[indexOfItem] = newValue
vm.items.length = newLength
解决方法
//1.
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
// Array.prototype.splice`
example1.items.splice(indexOfItem, 1, newValue)
//2.
example1.items.splice(newLength)
(9)遍历方法
<li v-for="n in even(numbers)">{{ n }}</li>
data: {
numbers: [ 1, 2, 3, 4, 5 ]
},
methods: {
even: function (numbers) {
return numbers.filter(function (number) {
return number % 2 === 0
})
}
}