VueDay03列表渲染循环渲染以及key的使用
Vue列表渲染,v-for的使用
①v-for="item in stars
②v-for="item,key in students
③v-for="item,key in students[0]
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<h3>明星列表</h3>
<ul>
<li v-for="item in stars">
{{item}}
</li>
</ul>
<h3>学生列表</h3>
<ul>
<li v-for="item in students">
<h4>{{item.studentName}}</h4>
<p>年龄:{{item.age}}---学校:{{item.school}}</p>
</li>
</ul>
<h3>学生列表(带索引值)</h3>
<ul>
<li v-for="item,key in students">
<h4>索引值:{{key}}{{item.studentName}}</h4>
<p>年龄:{{item.age}}---学校:{{item.school}}</p>
</li>
</ul>
<h3>循环对象</h3>
<ul>
<li v-for="item,key in students[0]">key:{{key}}----value:{{item}}</li>
</ul>
<!-- :src中的冒号是绑定的意思 全称是v-bind: -->
<img :src="students[0].imgheader" >
<h3>条件+循环渲染(将偶数年龄的学生渲染)</h3>
<!-- 先循环再判断 -->
<ol>
<li v-for="item,index in students" v-if="item.age%2==0" :key="index">
<h4>索引值:{{index}}{{item.studentName}}</h4>
<p>年龄:{{item.age}}---学校:{{item.school}}</p>
</li>
</ol>
</div>
<script type="text/javascript">
var app =new Vue({
el:"#app",
data:{
stars:["蔡徐坤","苏有朋","范冰冰","李晨"],
students:[
{
studentName:"小明",
age:16,
school:"清华",
imgheader:"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2369017631,3935728806&fm=26&gp=0.jpg"
},
{
studentName:"小黑",
age:17,
school:"北大"
},
{
studentName:"小红",
age:18,
school:"浙大"
},
{
studentName:"小红",
age:15,
school:"浙大"
}
]
}
})
</script>
</body>
</html>
循环渲染,v-for="todo in todos:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/vue.js" type="text/javascript"></script>
</head>
<body>
<div id="app-4">
<ol>
<li v-for="todo in todos">
{{todo.text}}
</li>
</ol>
</div>
<script type="text/javascript">
var app4 = new Vue({
el:'#app-4',
data:{
todos:[
{text:"学习 Javascript"},
{text:"学习 Vue"},
{text:"整个牛项目"}
]
}
})
</script>
<!-- 在控制台里,输入 app4.todos.push({ text: '新项目' }),会发现列表最后添加了一个新项目。 -->
</body>
</html>
key的使用,避免了复用现象,不加key区别的话,在相同的标签下输入的值会停留在输入框内:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<div v-if="isLogin" class="login" >
<h3>登录</h3>
用户名:
<input type="text" name="username" key="login" />
密码:
<input type="password" name="password" />
<button type="button">登录</button>
</div>
<div v-else class="register" >
<h3>注册</h3>
用户名:
<input type="text" name="username" key="register" />
密码:
<input type="password" name="password" />
<button type="button">注册</button>
</div>
<button @click="togglePage" type="button">切换登录注册页</button>
<script src="js/vue.js" ></script>
<script type="text/javascript">
let app = new Vue({
el:"#app",
data:{
isLogin:true
},
methods:{
togglePage:()=>{
app.isLogin = !app.isLogin;
}
}
})
</script>
</div>
</body>
</html>