Day 10 of Vue.js

How is v-model implemented

<input type="text" v-model="coupon">

<hr>

<input type="text" :value="coupon" @input="updateCoupon($event.target.value)">
new Vue({
    el: '#root',
    data: {
        coupon: 'coupon is here'
    },
    methods: {
        updateCoupon(input) {
            this.coupon = input;
        }
    }
});

The two input do the same trick.

##Custom Input Component
something new in vue 2.2
quoted from crouchingHamster on Laracast:

Using :value="code" in my component did not work for me. In the Vue docs, section "Form Input Components using Custom Events", it states for a component to work with v-model, it needs (specifically starting with v 2.2):

1) Accept 'value' prop
2) emit an input event with a new value

So in my code I changed props: ['code'] to props: ['value']

Also changed :value="code" to :value="value"

The 'value' prop can be customized to 'code' (Vue docs, section Customizing Component) by adding this to the component:

model: {
prop: 'code',
event: 'input'
},

Then you can keep props: ['code'] and :value="code" as seen in the video. Since I'm watching this video 3 months after launch so maybe things changed in Vue and why it wouldn't work without customizing.

sooo.. this is how you do it in Vue 2.2:

Vue.component('coupon', { 
    model: {
        prop: 'code',
        event: 'input'
    },
    props: ['code'],

    data(){
        return {
            validCodes: ['3154', '666', '999']
        }
    },

    template: `
        <input class="input" :value="code" @input="updateCode($event.target.value)" ref="input">
    `,

    methods: {
        updateCode(code) {
            if (this.validCodes.includes(code)) {
                alert('applied!!!!');

                this.$refs.input.value = code = '';

            }

            this.$emit('input', code);
        }
    },
});
<coupon v-model="coupon">

Leave a Reply

Your email address will not be published. Required fields are marked *