【问题标题】:Rendering input fields in Vuejs在 Vuejs 中渲染输入字段
【发布时间】:2023-03-23 23:06:01
【问题描述】:

我正在学习如何在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-model 中,以检查值是否设置正确我正在使用监视功能

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

但这总是给我错误:

未捕获的类型错误:无法读取 null 的属性“$emit”

我从This VueJS Documentation Link 获取了参考资料。帮我解决这个问题。谢谢。

【问题讨论】:

    标签: javascript html vue.js vuejs2 vue-component


    【解决方案1】:

    你应该使用箭头函数,因为你失去了回调中的范围:

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

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      相关资源
      最近更新 更多