Vue的基本使用案例
1.当鼠标经过一行时显示不一样的颜色
<style>
.active{
background: red;
}
</style>
<div id="app">
<ul>
<li v-for="(name, index) in names" :key="name" :class="{active : showActive(index)}"
@mouseover="setCurrentIndex(index)">{{name}}</li>
</ul>
</div>
<script>
const vue = new Vue({
el: '#app',
data: {
names: ['张三', '李四', '纪律委员','111', '222', '333'],
currentIndex: 0,
},
methods: {
changed() {
this.names.splice(0, 1, '111');
Vue.set(this.names, 1, '222');
},
setCurrentIndex(index) {
this.currentIndex = index
},
showActive(index) {
return this.currentIndex === index;
}
}
});
</script>
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200807143013947.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNTU1NTk1,size_16,color_FFFFFF,t_70)
2. 购物车页面
<style>
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th, td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
th {
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
</style>
<div id="app">
<table>
<tr>
<th></th>
<th>商品名称</th>
<th>上架时间</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="(good, index) in goods" :key="good.id">
<td v-text="good.id"></td>
<td v-text="good.name"></td>
<td v-text="good.importDate"></td>
<td >{{good.price | formatPrice}}</td>
<td>
<button @click="decrement(index, good.num)">-</button>
{{good.num}}
<button @click="increment(index, good.num)">+</button>
</td>
<td>
<button @click="removeCargo(index)">移除</button>
</td>
</tr>
</table>
<b>总计:</b>
<span v-text="totalPrice"></span>
</div>
<script>
const vue = new Vue({
el: '#app',
data: {
goods: [
{id: 1, name: '华为手机', importDate: '2006-10', price: 2000, num: 1},
{id: 2, name: '小米手机', importDate: '2006-11', price: 1900, num: 1},
{id: 3, name: 'OPPO手机', importDate: '2006-12', price: 1800, num: 1},
{id: 4, name: 'VIVO手机', importDate: '2007-01', price: 1700, num: 1},
{id: 5, name: '魅族手机', importDate: '2007-02', price: 1600, num: 1},
]
},
methods: {
decrement(index, num) {
var goodNum = --this.goods[index].num;
if (goodNum === 0){
this.removeCargo(index);
}
},
increment(index, num) {
this.goods[index].num++;
},
removeCargo (index) {
this.goods.splice(index, 1);
}
},
computed: {
totalPrice() {
let totalPrice = 0;
const cargos = this.goods;
for (let i = 0; i < cargos.length; i++){
totalPrice += (cargos[i].price * cargos[i].num);
}
return totalPrice.toFixed(2);
}
},
filters: {
formatPrice(price) {
return '¥ ' + price.toFixed(2);
}
}
});
</script>
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200807154712430.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNTU1NTk1,size_16,color_FFFFFF,t_70)