- 使用v-for渲染list中的内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>10</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
const app = Vue.createApp({
data() {
return {
listArray: ['xiaoming', 'li', 'doctor']
}
},
template: `
<div>
<div v-for="item in listArray">{{item}}</div>
</div>
`,
});
const vm = app.mount('#root')
</script>
</body>
</html>
2. 获取循环中的index:循环的每一项尽量给一个唯一的key值,这样相同的值不需要多次渲染,提高性能
<script>
const app = Vue.createApp({
data() {
return {
listArray: ['xiaoming', 'li', 'doctor']
}
},
template: `
<div>
<div v-for="(item, index) in listArray" :key="index">{{item}} -- {{index}}</div>
</div>
`,
});
const vm = app.mount('#root')
</script>
3. 循环对象:打印出value和key
<script>
const app = Vue.createApp({
data() {
return {
listArray: ['xiaoming', 'li', 'doctor'],
listObj: {
firstName: 'xiaoming',
lastName: 'li',
job: 'doctor'
}
}
},
template: `
<div>
<div v-for="(value, key, index) in listObj">{{value}} -- {{key}} -- {{index}}</div>
</div>
`,
});
const vm = app.mount('#root')
</script>
4. 向数组中添加数据:
<script>
const app = Vue.createApp({
data() {
return {
listArray: ['xiaoming', 'li', 'doctor'],
listObj: {
firstName: 'xiaoming',
lastName: 'li',
job: 'doctor'
}
}
},
methods: {
handleAddBtnClick() {
this.listArray.push('hello')
}
},
template: `
<div>
<div v-for="(item, index) in listArray" :key="index">{{item}} -- {{index}}</div>
</div>
<button @click="handleAddBtnClick">新增</button>
`,
});
const vm = app.mount('#root')
</script>
- 像对象里添加字段,然后显示
<script>
const app = Vue.createApp({
data() {
return {
listArray: ['xiaoming', 'li', 'doctor'],
listObj: {
firstName: 'xiaoming',
lastName: 'li',
job: 'doctor'
}
}
},
methods: {
handleAddBtnClick() {
// this.listArray.push('hello')
this.listObj.age = 100;
this.listObj.sex = 'male';
}
},
template: `
<div>
<div v-for="(value, key, index) in listObj" :key="index">{{value}} -- {{key}}</div>
</div>
<button @click="handleAddBtnClick">新增</button>
`,
});
const vm = app.mount('#root')
</script>