Vuejs2 使用道具初始化v型模型?
我正在尝试创建一个使用v-model的Vue组件。v模型的初始值最终将来自父组件或数据存储。我试图开始工作的第一步是用属性初始化v模型。我尝试了以下方法但没有成功:Vuejs2 使用道具初始化v型模型?,vuejs2,vue-component,Vuejs2,Vue Component,我正在尝试创建一个使用v-model的Vue组件。v模型的初始值最终将来自父组件或数据存储。我试图开始工作的第一步是用属性初始化v模型。我尝试了以下方法但没有成功: <template> <div> <textarea v-model="text" ></textarea> </div> </template> <script> export default { prop
<template>
<div>
<textarea
v-model="text"
></textarea>
</div>
</template>
<script>
export default {
props: { initialValue: String },
data() {
return {
text: this.props ? this.props.initialValue : 'This is a test'
}
}
}
</script>
导出默认值{
道具:{initialValue:String},
数据(){
返回{
text:this.props?this.props.initialValue:“这是一个测试”
}
}
}
并从父级使用它,如下所示:
<MyComponent initialValue="Hello World" />
组件显示“这是一个测试”,而不是我想要的“Hello World”。初始化使用v型模型的组件的正确方法是什么
编辑
我现在已经放弃了v型模型,并提出了这种方法。。。但感觉不是很“Vue-ly”。。我本质上是在研究textarea(eve.srcmelement.value.length)的实现细节,而我觉得我应该研究一个域对象。。。有更好的方法吗?注意,在textChange事件中,我最终将发出其他组件的通知
<template>
<div>
<textarea
:value="initialValue"
@change="textChange"
@keyup="textChange"
placeholder="Type your text here"
></textarea>
</div>
</template>
<script>
export default {
props: { initialValue: String },
methods: {
textChange: function(evt) {
console.log('Length: ' + evt.srcElement.value.length)
}
}
}
</script>
导出默认值{
道具:{initialValue:String},
方法:{
文本更改:功能(evt){
console.log('Length:'+evt.srcielement.value.Length)
}
}
}
v-model
利用值
道具。您需要发出input
事件,然后更新父级中的值
MyComponent.vue
<template>
<div>
<textarea :value="value" @input="$emit('input', $event.target.value)"></textarea>
</div>
</template>
<script>
export default {
props: ['value']
}
</script>
<MyComponent v-model="val"/>
导出默认值{
道具:['value']
}
Parent.vue
<template>
<div>
<textarea :value="value" @input="$emit('input', $event.target.value)"></textarea>
</div>
</template>
<script>
export default {
props: ['value']
}
</script>
<MyComponent v-model="val"/>
有关更多详细信息,请参阅。可能与我编辑的问题重复。据我所知,链接文章中的解决方案与我的问题并不完全相关。我不理解Parent.vue v-model=“val”。你能解释一下这一部分吗?
val
将是父组件中的一个数据属性,即data:()=>({val:'foo'})
我尝试过,但性能不太好。。。每按一次按键都会发出大量的事件和数据,这是预期的行为。考虑使用或实现自己的函数来限制事件的数量。