在 Vuejs 中渲染输入字段 [英] Rendering input fields in Vuejs
问题描述
我正在学习如何在 Vuejs
中渲染 HTML 内容我正在尝试构建一个从 render
函数生成的小型输入组件.它看起来像这样:
出口默认{名称:尼特输入",方法: {},道具: {标签:字符串,提示:字符串,错误:字符串,占位符:字符串},渲染(创建元素){//帮助动作文本让 helpText = this.hint ?createElement('span', { class: 'm-form__help' }, this.hint) : ''//错误文本让 errorText = this.error ?createElement('span', { class: 'm--font-danger' }, this.error) : ''return createElement('div', { class: ''}, [createElement('label', this.label),创建元素('输入',{类:'表单控制m-输入',attrs: { type: this.type, placeholder: this.placeholder },domProps: { value: self.value},在: {输入:函数(事件){this.$emit('input', event.target.value)}}}),帮助文本,错误文本])}}
在调用此组件时,我正在执行以下操作:
<div class="form-group m-form__group">我希望将值存储到 v-model 中,以检查是否正确设置了值我正在使用监视功能
观看:{电子邮件 () {console.log('Email v-model 定义为 '+this.email)},密码() {console.log('Password v-model 定义为 '+this.password)}}
但这总是给我错误:
<块引用>未捕获的类型错误:无法读取 null 的属性 '$emit'
我从 这个 VueJS 文档链接中获取了参考资料一>.帮我解决这个问题.谢谢.
解决方案 你应该使用箭头函数,因为你失去了回调中的作用域:
on: {输入:(事件)=>{this.$emit('input', event.target.value)}}
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.
解决方案 you should use arrow function since you're loosing the scope inside that callback :
on: {
input:(event)=> {
this.$emit('input', event.target.value)
}
}
这篇关于在 Vuejs 中渲染输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文