1.v-if
v-if相当好理解,这里我就只贴实例代码了
<div id="app">
<p v-if="true">现在你看到我了</p>
<p v-if="false">现在你看不到我了</p>
<p v-if="seen">现在看得到,因为seen为true</p>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
seen: true
}
})
</script>
2.v-for
2.1 v-for的简单使用,v-for 中 in 和 of 的区别
<body>
<div id="app">
<div v-for="todo in todos">
{{ todo.text }}
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
todos: [
{ text: '学习 JavaScript' },
{ text: '学习 Vue' },
{ text: '整个牛项目' }
]
}
})
</script>
</body>
此处可写为item in todos也无妨,只要内容写为{{item.text}}即可,这样就实现了遍历todos变量。
输出结果如下
2.2 v-for 中 in 和 of 的区别
如果你比较细心你会发现上面的代码中,v-for=“todo in todos”,似乎是在使用js中的for in语法,得到的应该是对象数组的下标才对,怎么直接得到了值呢?因为在 vue 的 v-for 中, in 和 of 并没有区别,你你把它写成v-for="todo of todos"也是一样的效果
2.3 高级一点点的v-for
不过如果大家如果有用vue的相关插件,会发现你输入vfor的时候,它弹出来的是这样的东西
其中的 :key是v-bind:key的缩写,这一点将在下一篇的笔记中提到,此时可以先放置不管v-bind
v-for="(item, index) in items" :key="index"
我们改写一下代码,改写为这样
<div v-for="(item, index) in todos" :key="index">
{{ index }} ------- {{ item.text }}
</div>
输出的效果如下
其实v-for中还有更多的参数可以调用,接下来我们使用普通的对象的时候,作为举例
<body>
<div id="app">
<div v-for="(item, key, index) of userInfo">
{{ item }} ----- {{ key }} ------ {{ index }}
</div>
</div>
<script>
let vm = new Vue({
el: '#app',
data: {
userInfo: {
name: 'dell',
age: 20,
gender: 'male',
salary: 'secret'
}
}
})
</script>
</body>
输出如上图所示,为什么此处不用对象数组作为实例呢?因为对象数组中index和key是同一个值,大家可以自行测试一下。