Rendering input fields in Vuejs

ghz 1years ago ⋅ 7306 views

Question

I'm learning on how to render HTML contents in Vuejs I'm trying to build a small input component which gets generated from render function. It looks something like this:

export default {
    name: "nits-input",
    methods: {

    },
    props: {
        label: String,
        hint: String,
        error: String,
        placeholder: String
    },
    render (createElement) {

        //Help action text
        let helpText = this.hint ? createElement('span', { class: 'm-form__help' }, this.hint) : ''

        //Error Text
        let errorText = this.error ? createElement('span', { class: 'm--font-danger' }, this.error) : ''

        return createElement('div', { class: ''}, [
            createElement('label', this.label),
            createElement('input', {
                class: 'form-control m-input',
                attrs: { type: this.type, placeholder: this.placeholder },
                domProps: { value: self.value},
                on: {
                    input: function (event) {
                        this.$emit('input', event.target.value)
                    }
                }
            }),
            helpText, errorText
        ])
    }
}

While calling this component I'm doing below:

<div class="form-group m-form__group">
    <nits-input
            label="Email Address"
            type="email"
            hint="We'll never share your email with anyone else."
            placeholder="Enter email"
            v-model="email"
    >
    </nits-input>
</div>
<div class="form-group m-form__group">
    <nits-input
            label="Password"
            type="password"
            placeholder="Enter password"
            v-model="password"
    >
    </nits-input>
</div>

I want the value to be stored into v-model, to check the values are being set properly I'm using a watch function

watch: {
    email () {
        console.log('Email v-model defined as '+this.email)
    },
    password() {
        console.log('Password v-model defined as '+this.password)
    }
}

But this always gives me error:

Uncaught TypeError: Cannot read property '$emit' of null

I've taken the references from This VueJS Documentation Link. Help me out in this. Thanks.


Answer

you should use arrow function since you're loosing the scope inside that callback :

on: {
   input:(event)=> {
      this.$emit('input', event.target.value)
             }
    }