温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Vue怎么实现一个购物车功能

发布时间:2020-12-21 15:19:45 来源:亿速云 阅读:185 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关使用Vue怎么实现一个购物车功能,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

HTML代码块

<body>
 <div id="app">
 <div v-if="books.length">
 <table>
  <thead>
  <tr>
   <th></th>
   <th>书籍名称</th>
   <th>出版日期</th>
   <th>价格</th>
   <th>购买数量</th>
   <th>操作</th>
  </tr>
  </thead>

  <tbody>
  <tr v-for="(itme,index) in books">
   <td>{{itme.id}}</td>
   <td>{{itme.name}}</td>
   <td>{{itme.date}}</td>
   <!-- showPrice过滤器 -->
   <td>{{itme.price | showPrice}}</td>
   <td>
   <!-- 动态绑定disabled,当数量小于1时 禁止点击按钮-->
   <button @click="decrement(index)" :disabled="itme.count <= 1">-</button>
   {{itme.count}}
   <button @click="increment(index)">+</button>
   </td>
   <td><button @click="Handle(index)">移除</button></td>
  </tr>
  </tbody>
 </table>
 <h3>总价格:{{totalPrice | showPrice}}</h3>
 </div>
 <h3 v-else>购物车为空</h3>
 </div>
</body>

css代码块

table{
 border: 1px solid #e9e9e9;
 border-collapse: collapse;
 border-spacing: 0;
}
th,td{
 padding: 8px 16px;
 border: 1px solid #e9e9e9;
 text-align: left;
}
th{
 background: #f7f7f7;
 color: #5c6b77;
 font-weight: 600;
}

Vue.js代码块

const app = new Vue({
 el:'#app',
 data:{
 books:[
  { 
  
  id:1,
  name:'《算法议论》',
  date:'2001-1',
  price:85.00,
  count:1
 },
 { 
  id:2,
  name:'《编程珠玑》',
  date:'2002-1',
  price:65.00,
  count:1
 },
 { 
  id:3,
  name:'《Unix编程艺术》',
  date:'2000-1',
  price:59.00,
  count:1
 },
 { 
  id:4,
  name:'《代码大全》',
  date:'2005-1',
  price:135.00,
  count:1
 },
 ]
 },

 /**
 * 使用普通方法
 */
 methods:{
 //获取小数点的方法
 // getFinalPrice(price){
 // return '¥' + price.toFixed(2);
 // }

 //点击事件
 increment(index){
  this.books[index].count++;
 },
 decrement(index){
  this.books[index].count--;
 },
 Handle(index){
  this.books.splice(index,1);
 }
 },
 computed:{
 totalPrice(){
  let totalPrice = 0;
  for(let i = 0; i < this.books.length; i++){
  totalPrice += this.books[i].price * this.books[i].count;
  }
  return totalPrice;
 }
 },
 /**
 * 使用过滤器获取小数点
 */
 filters:{
 showPrice(price){
  return '¥' + price.toFixed(2);
 }
 }
})

上述就是小编为大家分享的使用Vue怎么实现一个购物车功能了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI