Ad

Apply A Discount Using VueJS And Laravel

- 1 answer

I haven't gone down the road of creating custom components, I have got it checking for the coupon code now I need to know how I can set a the cost then apply the discount.

Heres the JS I have currently

new Vue({
el: '#coupons',

data: function() {
    return {
        coupon: {
            code: '',
            description: '',
            discount: 0
        },

        valid: false
    };
},

methods: {
    validate: function() {
        this.$http.get('/coupons/' + this.coupon.code)
            .success(function(coupon) {
                this.coupon = coupon;
                this.valid = true;
                this.coupon.description = 'Great! You entered a valid coupon.';

            })
            .error(function() {
                this.coupon.code = '';
                this.coupon.description = 'Sorry, that coupon does not exist.';
            });
    }
}
});

Anyone advise on how to achieve this based on the above please :) Presumably I would need to pass the value from Laravel to the JS, again how would I achieve this, then apply the discount, would I se v-model for example to use two way binding?

Ad

Answer

why not echo the price into a javascript object?

(function(globals){
   globals.price = {{ $somePrice }};
})(window.globals || (window.globals ={}));

then share the state with your vuejs component,

new Vue({
   data:{
      coupon: {
        code: '',
        description: '',
        discount: 0
      },
      valid: false,
      price: window.globals.price
   }
});

You can trigger the validation via several events depending on your choice; say for example you want to fire the ajax request when the user stops entering on the input

then you can go <input v-model="coupon.code" type="text" @keyup="validate() | debounce 1000">

the code above will call the method validate a second after the last keyup

now for the validate function

...
    validate: function() {
        // assign this to another variable to make it accessible in the promise scope
        var _this = this;
        this.$http.get('/coupons/' + this.coupon.code).then(function(response) {
             // you can just pass a negative response  (false or null)from laravel
             if (response) {
                  _this.coupon = response;

             }

        });

    }

finally you can use vuejs' computed property to update the display of the discounted amount.

computed: {
    discounted: function() {
        return this.price - this.coupon.discount;
    }
}

and in the view

<span>{{ discounted }}</span>

you should still pass the coupon to the backend and recalculate the discounted price from there when the user buys or whatever he does.

Sources: http://vuejs.org/guide/events.htmlhttp://vuejs.org/guide/computed.html

Ad
source: stackoverflow.com
Ad