v-for指令使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<!--
1.导入开发版本的Vue.js
2.创建Vue实例对象,设置el属性和data属性
3.使用模板语法将数据渲染到页面上
-->
<body>
<div id="app">
<!-- 利用v-for展示普通数组 -->
<ul>
<!-- 利用v-for指令循环生成标签 -->
<li v-for="item in campus">
校区:{{item}}
</li>
</ul>
<ul>
<!-- 还可以使用索引,,注意语法格式,括号里第一个元素表示数组元素,第二个参数表示数组索引-->
<li v-for="(item,index) in campus">
{{index+1}}校区:{{item}}
</li>
</ul>
<!--------------分割线----------------->
<button @click="add">增加菜品</button>
<button @click="remove">删除菜品</button>
<!-- 利用v-for展示对象数组 -->
<h4 v-for=" item in vegetable">{{item.name}}</h4>
</div>
<script src="./vue.js"></script>
<script>
var app = new Vue({
el: "#app",
data: {
campus: ["北京校区", "上海校区", "上海校区"],
vegetable: [{
name: '西蓝花'
}, {
name: '大白菜'
}]
},
methods: {
add: function() {
this.vegetable.push({
name: '芹菜'
})
},
remove: function() {
this.vegetable.shift()
}
}
})
</script>
</body>
</html>
运行效果