在Vue.js中渲染输入字段 [英] Rendering input fields in Vuejs

查看:160
本文介绍了在Vue.js中渲染输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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

但这总是给我错误:

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

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

我已经从此VueJS文档链接.帮我解决这个问题.谢谢.

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

推荐答案

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

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

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

这篇关于在Vue.js中渲染输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆