【VUE】vue入门之实现简易的购物车组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30604453/article/details/80924631

vue初学者

由于之前用惯了angular了,所以学起vue来还是比较得心应手的,昨天大概看了一遍vue的API文档,今天用vue实现一个简易的购物车组件

1.全局安装vue-cli命令行工具

npm install vue-cli --g

2.用vue命令行初始化项目

vue init webpack shoppingCart

初始化完毕如下

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>

猜你喜欢

转载自blog.csdn.net/qq_30604453/article/details/80924631
今日推荐