在Vue.js中渲染输入字段

时间:2018-12-26 19:17:33

标签: javascript vue.js vuejs2 vue-component

我正在学习如何在Vuejs中呈现HTML内容,我正在尝试构建一个小的输入组件,该组件由render函数生成。看起来像这样:

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
        ])
    }
}

在调用此组件时,我正在执行以下操作:

<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>

我希望将值存储到v模型中,以检查值是否正确设置,我正在使用监视功能

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

但这总是给我错误:

  

未捕获的TypeError:无法读取null的属性'$ emit'

我从This VueJS Documentation Link那里获得了参考。帮我解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:3)

您应该使用箭头功能,因为您失去了该回调函数的作用域:

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