Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Rendering input fields in Vuejs

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...