【VUE】vue入门之实现简易的购物车组件
vue初学者由于之前用惯了angular了,所以学起vue来还是比较得心应手的,昨天大概看了一遍vue的API文档,今天用vue实现一个简易的购物车组件先上仓库地址https://gitee.com/wuchunling/shoppingCart.git先看效果图1.全局安装vue-cli命令行工具npm install vue-cli --g2.用vue命令行初始化项...
·
vue初学者
由于之前用惯了angular了,所以学起vue来还是比较得心应手的,昨天大概看了一遍vue的API文档,今天用vue实现一个简易的购物车组件
先上仓库地址https://gitee.com/wuchunling/shoppingCart.git
先看效果图
1.全局安装vue-cli命令行工具
npm install vue-cli --g
2.用vue命令行初始化项目
vue init webpack shoppingCart
cd shoppingCart
npm install
初始化完毕如下
3.进入src/components,新建ShoppingCart.vue文件
编写内容如下
<template lang="html">
<div>
<table id="shopping-list">
<thead>
<tr>
<th colspan="3">购物车</th>
</tr>
<tr>
<th>名称</th><th>价格</th><th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in list">
<td>{{item.name}}</td><td>{{item.price}}</td>
<td @click="delGoods(index)" class="del-goods">删除</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">总价</td><td>{{totalPrice}}(共{{counts}}件商品)</td>
</tr>
</tfoot>
</table>
<div class="goods-list">
<h3>商品列表</h3>
<ul>
<li v-for="(item,index) in goods">{{item.name}} {{item.price}} <a @click="addGoods(index)">加入购物车</a> </li>
</ul>
</div>
</div>
</template>
<script>
export default {
name:"ShoppingCart",
data(){
return{
list:[
{name:"柠檬茶",price:18.0},
{name:"维他奶",price:16.5},
{name:"矿泉水",price:3.5}
],
goods:[
{name:"笔记本",price:5.0},
{name:"键盘",price:30.0},
{name:"便利贴",price:2.0},
{name:"柠檬茶",price:18.0},
{name:"维他奶",price:16.5},
{name:"矿泉水",price:3.5}
]
}
},
computed:{
totalPrice(){
var num = 0;
for (var i = 0; i < this.list.length; i++) {
num += this.list[i].price;
}
return num.toFixed(1);
},
counts(){
return this.list.length;
}
},
methods:{
delGoods(index){
this.list.splice(index,1);
},
addGoods(index){
this.list.push(this.goods[index]);
}
}
}
</script>
<style lang="css">
.del-goods,a{
cursor: pointer;
}
ul{
list-style-type: none;
}
</style>
4.修改src目录下的App.vue
<template>
<div id="app">
<ShoppingCart/>
</div>
</template>
<script>
import ShoppingCart from "./components/ShoppingCart"
export default {
name: 'App',
components: {
ShoppingCart
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
npm run dev 可以在 localhost:8080看到效果
更多推荐
已为社区贡献4条内容
所有评论(0)