用vue.js重構訂單計算頁面


在很久很久以前做過一個很糟糕的訂單結算頁面,雖然里面各區域(收貨地址)使用模塊化加載,但是偶爾會遇到某個模塊加載失敗的問題導致訂單提交的數據有誤。

大致問題如下:

1. 每個模塊都采用usercontrol(收貨地址、配送范圍、支付方式、優惠券等等),維護起來很困難。

2. 每個模塊的加載都是一個Ajax請求,並且根據前后順序關系加載多個模塊即多個Ajax請求。比如用戶修改收貨地址后系統重新計算配送方式和支付方式,並刷新配送方式、支付方式、訂單總金額等數據,一般情況下沒問題,但偶爾會遇到某個模塊加載失敗導致頁面數據顯示不正確。

 

所以必須要重構訂單結算頁面,使用模版引擎或Vue.js,這里就采用Vue.js重構頁面。

訂單結算頁的頁面區域模塊大致如下:

<div class="order-form">
   <div>收貨地址區域</div>
   <div>配送范圍區域</div>
   <div>支付方式區域</div>
   <div>優惠券區域</div>
   <div>商品列表區域</div>
   <div>金額匯總區域</div>
</div>

根據頁面區域定義數據模型,大致如下:

AddressList:用戶收貨地址列表
DeliveryList:配送方式
PaymentList:支付方式
DefaultAddress:用戶默認收貨地址

其他數據用於提交表單或頁面顯示金額用,就不介紹了。

初始化Vue對象

var model = {};

var vue = new Vue({
    el: '.order-form',
    data: model,
    computed: {
    },
    methods : {
    }
});

 

收貨地址

view

    <ul>
    <template v-if="AddressList.length">
    <li v-for="(address,index) in AddressList">
        <label>
        <input type="radio" name="addressId" :value="address.AddressId" v-model="AddressId" :checked="address.AddressId == AddressId" />                            
            {{ address.Address }}
        </label>
    </li>
    </template>
    <template v-else>
        暫無收貨地址
    </template>
    <li>
        <a href="javascript:;" v-on:click="addressAdd">新建收貨地址</a>
    </li>
    </ul>

 其中v-model 采用的是雙向數據綁定,它會根據控件類型自動選取正確的方法來更新model.AddressId。

view里綁定事件用v-on:事件名稱

vue添加增加收貨地址事件,這是Demo就寫個簡單的例子,建議用Ajax彈出層讓用戶填寫收貨地址。

    methods : {
        addressAdd : function(){
            model.AddressList.push({AddressId : mode.AddressList.length + 1, Address : "隨機添加的收貨地址" + math.random()});
        }
    }

 效果如下:

 

 配送方式:

View代碼:

<li v-for="(delivery,index) in DeliveryList">
 <label>
   <input type="radio" name="deliveryId" :value="delivery.DeliveryId" v-bind:checked="delivery.DeliveryId == DeliveryId" 
v-on:click="deliverySelect(delivery)" />
 {{ delivery.DeliveryName }}(運費:¥{{ delivery.DeliveryFee }}) </label>
 </li>

Vue代碼:

deliverySelect :function(delivery){
   model.DeliveryId = delivery.DeliveryId;
   model.DeliveryFee = delivery.DeliveryFee;
},

效果如下:

 

訂單金額顯示:

View:

<div class="all_price">
            訂單總金額:
            <b>¥{{ orderAmount }}</b>
            = 商品總金額:
            <b>¥{{ ProductAmount }}</b>
            + 運費:
            <b>¥{{ DeliveryFee }}</b>
            - 優惠券:
            <b>¥{{ CouponAmount }}</b>
 </div>

Vue代碼:

computed: {
     orderAmount : function(){
        return this.ProductAmount + this.DeliveryFee - this.CouponAmount;
     }
 },

 

其他部分代碼以此類推,就是綁定數據和事件就可以。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM