小白学习 Vue 系列目录
条件渲染
<div v-if="type === 'A'">A</div>
<div v-else-if="type === 'B'">B</div>
<div v-else-if="type === 'C'">C</div>
<div v-else>Not A/B/C</div>
v-if VS v-show
v-if是插入或删除v-show是可见或者不可见
不推荐在同一元素上使用v-if和v-for,v-for具有比v-if更高的优先级(有点像 Swift 中的 for where)
列表渲染
v-for="(item, index) in array"
v-for="(value, key, index) in object"
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- Vue.js v2.6.12 -->
</head>
<body>
<div 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>
</div>
<hr/>
</body>
<script type="text/javascript">
Vue.component('todo-item', {
props: ['title'],
template: '\
<li>\
{{ title }}\
<button v-on:click="$emit(\'remove\')">Remove</button>\
</li>\
',
})
var app = new Vue({
el: '#todo-list-example',
// created: function() {
// this.nextTodoId = this.todos.length + 1
// },
data: {
newTodoText: '',
todos: [
{ id: 1, title: 'Do the dishes' },
{ id: 2, title: 'Take out of trash' },
{ id: 3, title: 'Mow the lawn' },
],
nextTodoId: 4,
},
methods: {
addNewTodo: function () {
if (!this.newTodoText) return
this.todos.push({
id: this.nextTodoId++,
title: this.newTodoText
})
this.newTodoText = ""
}
}
})
</script>
</html>