根据文档,
<input v-model="something"> 是相同的:
<input
v-bind:value="something"
v-on:input="something = $event.target.value">
Run Code Online (Sandbox Code Playgroud)
所以我尝试了以下并且它有效:
<input v-model='sample'>
<input v-bind:value='sample' v-on:input="sample = $event.target.value" >
Run Code Online (Sandbox Code Playgroud)
现在,当我在自定义组件中尝试相同的操作时,它会触发一个错误:
VM99:2Uncaught TypeError: 无法读取未定义的属性“值”
我在这里缺少什么才能使它工作?谢谢。
Ant*_*Man 10
我在文档之后遇到了同样的问题:https :
//vuejs.org/v2/guide/components.html#Using-v-model-on-Components
您可以通过$event代替直接获取值$event.target.value
这是带有工作代码的文档示例:
Vue.component('custom-input', {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event)"
>
`
})
Run Code Online (Sandbox Code Playgroud)
现在v-model应该与此组件完美配合:
<custom-input v-model="searchText"></custom-input>
Run Code Online (Sandbox Code Playgroud)
input您正在事件处理程序内发出事件input。
所以这里发生的问题是:
首先input当你输入<input>
input: function(event) {
self.$emit("input", event.target.value) // 2
}
Run Code Online (Sandbox Code Playgroud)
您将输入值发出到目标元素。
第二次发射是由处理程序本身引起的,
input: function(event) {
/* the value of event is no longer a DOM el
instead it is a string value which doesn't have a target property
it throws an error on the console. */
self.$emit("input", event.target.value)
}
Run Code Online (Sandbox Code Playgroud)
未捕获的类型错误:无法读取未定义的属性“值”
这是工作小提琴。
编辑
另外,在您的组件 HTML 中,您期望$event有一个targetwhich 进一步应该有一个value属性。
self.$emit("input", event.target.value)
Run Code Online (Sandbox Code Playgroud)
因此,您在这里发出一个值,这是行不通的。
| 归档时间: |
|
| 查看次数: |
3929 次 |
| 最近记录: |