用vue2.0实现一个列表渲染
时间: 2024-03-13 17:44:45 浏览: 130
好的,下面是一个使用 Vue 2.0 实现列表渲染的示例:
首先,我们需要在 Vue 实例中定义一个数组,用于存储列表数据。例如:
```javascript
new Vue({
el: '#app',
data: {
list: ['apple', 'banana', 'orange']
}
})
```
接下来,在 HTML 中使用 `v-for` 指令来渲染数组中的每一项。例如:
```html
<div id="app">
<ul>
<li v-for="item in list">{{ item }}</li>
</ul>
</div>
```
在上面的示例中,`v-for` 指令用于循环遍历 `list` 数组中的每一项,并将每一项渲染为一个 `li` 元素。
最终,Vue 会将数组中的每一项动态渲染到页面上,生成一个包含所有列表项的无序列表。
相关问题
vue2.0实现经典购物车案例
好的,下面是一个简单的 Vue2.0 实现经典购物车案例的示例代码:
HTML:
```
<div id="app">
<div class="cart">
<h2>购物车</h2>
<ul>
<li v-for="(item, index) in cartItems" :key="index">
{{ item.name }} - {{ item.quantity }} - {{ item.price }}
<button @click="removeFromCart(item)">删除</button>
</li>
</ul>
<p>总价:{{ cartTotal }}</p>
</div>
<div class="products">
<h2>商品列表</h2>
<ul>
<li v-for="(item, index) in availableItems" :key="index">
{{ item.name }} - {{ item.price }}
<button @click="addToCart(item)">添加到购物车</button>
</li>
</ul>
</div>
</div>
```
JS:
```
var app = new Vue({
el: '#app',
data: {
cartItems: [],
availableItems: [
{ name: '商品1', price: 10 },
{ name: '商品2', price: 20 },
{ name: '商品3', price: 30 },
{ name: '商品4', price: 40 },
{ name: '商品5', price: 50 }
]
},
computed: {
cartTotal: function() {
var total = 0;
for (var i = 0; i < this.cartItems.length; i++) {
total += this.cartItems[i].price * this.cartItems[i].quantity;
}
return total;
}
},
methods: {
addToCart: function(item) {
var found = false;
for (var i = 0; i < this.cartItems.length; i++) {
if (this.cartItems[i].name === item.name) {
this.cartItems[i].quantity++;
found = true;
}
}
if (!found) {
this.cartItems.push({
name: item.name,
price: item.price,
quantity: 1
});
}
},
removeFromCart: function(item) {
var index = this.cartItems.indexOf(item);
this.cartItems.splice(index, 1);
}
}
});
```
其中,`cartItems` 表示购物车中的商品列表,`availableItems` 表示可供选择的商品列表。通过 `v-for` 指令循环渲染商品列表和购物车列表。`addToCart` 方法用于添加商品到购物车,如果购物车中已经有该商品,则增加其数量,否则将该商品添加到购物车中;`removeFromCart` 方法用于从购物车中删除商品;`cartTotal` 计算购物车中所有商品的总价。
阅读全文
相关推荐

















