我已经能够在自定义组件上完成单层深度的v-模型双向绑定,但需要更深入一层。带v模型的Vue.js组件
当前工作代码:
<template lang="html">
<div class="email-edit">
<input ref="email" :value="value.email" @input="updateInput()"/>
<input ref="body" :value="value.body" @input="updateInput()"/>
</div>
</template>
<script type="text/javascript">
import LineEditor from './LineEditor.vue'
export default {
components: {
LineEditor
},
computed: {
},
methods: {
updateInput: function(){
this.$emit('input',{
email: this.$refs.email.value,
body: this.$refs.body.value
})
}
},
data: function(){
return {}
},
props: {
value: {
default: {
email: "",
body: ""
},
type:Object
}
}
}
</script>
像这样来使用:<email-edit-input v-model="emailModel" />
但是,如果我加入这一块,价值不再传播向上:
<div class="email-edit">
<line-editor ref="email" :title="'Email'" :value="value.email" @input="updateInput()"/>
<input ref="body" :value="value.body" @input="updateInput()"/>
</div>
</template>
<script type="text/javascript">
import LineEditor from './LineEditor.vue'
export default {
components: {
LineEditor
},
computed: {
},
methods: {
updateInput: function(){
this.$emit('input',{
email: this.$refs.email.value,
body: this.$refs.body.value
})
}
},
data: function(){
return {}
},
props: {
value: {
default: {
email: "",
body: ""
},
type:Object
}
}
}
</script>
使用这第二个自定义组件:
<template lang="html">
<div class="line-edit">
<div class="line-edit__title">{{title}}</div>
<input class="line-edit__input" ref="textInput" type="text" :value="value" @input="updateInput()" />
</div>
</template>
<script type="text/javascript">
export default {
components: {
},
computed: {
},
methods: {
updateInput: function(){
this.$emit('input', this.$refs.textInput.value)
}
},
data: function(){
return {}
},
props: {
title:{
default:"",
type:String
},
value: {
default: "",
type: String
}
}
}
</script>
第一个代码块只用输入即可正常工作。但是,使用两个自定义组件似乎没有通过这两个组件冒泡,只有LineEditor。如何通过所有自定义组件获取这些值,而不管嵌套?
这些似乎是一个更完整的解决方案。我已经将它添加到我的代码库中,并且它可以工作。只是为了确保我遵循你的逻辑。道具传递给孩子,孩子使用观察者来捕捉父母对道具的任何变化并相应地调整其实例范围变量。实例范围变量data用于输入作为v-model来维护用户编辑的内容,并通过emit on输入传递给父级。这是否涵盖了你的逻辑链? – steventnorris
@steventnorris你明白了。 – Bert