vue2.0 之列表渲染-v-for

时间:2023-03-09 09:38:52
vue2.0 之列表渲染-v-for

v-for 数组渲染

App.vue代码

<template>
<div>
<ul>
<li v-for="item in list"> {{ item.name }} - {{ item.price }}</li>
</ul>
<ul>
<li v-for="item in list" v-text="item.name + '-' + item.price"></li>
</ul>
<ul>
<li v-for="(item, index) in list"> {{ index }} - {{ item.name }} - {{ item.price }}</li>
</ul>
</div>
</template> <script>
export default {
data () {
return {
list: [
{
name: 'apple 7S',
price: 6188
},
{
name: 'huawei P10',
price: 4288
},
{
name: 'mi6',
price: 2999
}
]
}
}
}
</script> <style>
html {
height: 100%;
}
</style>

页面效果

vue2.0 之列表渲染-v-for

v-for 对象渲染

App.vue代码

<template>
<div>
<ul>
<li v-for="value in objlist"> {{ value }}</li>
</ul>
<ul>
<li v-for="(key, value) in objlist"> {{ key + ':' + value }}</li>
</ul>
</div>
</template> <script>
export default {
data () {
return {
objlist: {
name: 'apple 7S',
price: 6188,
color: 'red',
size: 6.0
}
}
}
}
</script> <style>
html {
height: 100%;
}
</style>

页面显示

vue2.0 之列表渲染-v-for

v-for  子组件渲染

创建./components/hello.vue文件

<template>
<div>
{{ hello }}
</div>
</template> <script>
export default {
data () {
return {
hello: 'i am component hello'
}
}
}
</script> <style scoped>/**/
h1 {
height: 100px;
}
</style>

App.vue代码

<template>
<div>
<componenthello v-for="(key, value) in objlist"></componenthello>
</div>
</template> <script>
import componenthello from './components/hello'
export default {
components: {
componenthello
},
data () {
return {
objlist: {
name: 'apple 7S',
price: 6188,
color: 'red',
size: 6.0
}
}
}
}
</script> <style>
html {
height: 100%;
}
</style>

页面显示

vue2.0 之列表渲染-v-for

列表数据的同步更新

案例一:

<template>
<div>
<ul>
<li v-for="item in list"> {{ item.name }} - {{ item.price }}</li>
</ul>
<button v-on:click="addItem">addItem</button>
</div>
</template> <script>
export default {
data () {
return {
list: [
{
name: 'apple 7S',
price: 6188
},
{
name: 'huawei P10',
price: 4288
},
{
name: 'mi6',
price: 2999
}
]
}
},
methods: {
addItem () {
this.list.push({
name: 'meizu',
price: 2499
})
}
}
}
</script> <style>
html {
height: 100%;
}
</style>

vue2.0 之列表渲染-v-for

vue2.0 之列表渲染-v-for

vue2.0 之列表渲染-v-for

案例二

<template>
<div>
<ul>
<li v-for="item in list"> {{ item.name }} - {{ item.price }}</li>
</ul>
<button v-on:click="addItem">addItem</button>
</div>
</template> <script>
import Vue from 'vue'
export default {
data () {
return {
list: [
{
name: 'apple 7S',
price: 6188
},
{
name: 'huawei P10',
price: 4288
},
{
name: 'mi6',
price: 2999
}
]
}
},
methods: {
addItem () {
Vue.set(this.list, 1, {
name: 'meizu',
price: 2499
})
}
}
}
</script> <style>
html {
height: 100%;
}
</style>

点击按钮前

vue2.0 之列表渲染-v-for

点击按钮后

vue2.0 之列表渲染-v-for