子组件的v模型和子组件Vue内的v模型 [英] v-model for child component and v-model inside child component Vue
问题描述
有没有办法简化此代码?
Is there a way to simplify this code?
该按钮还应更改孩子的localValue。
Vue.component('my-input', {
template: `
<div>
<b>My Input:</b> <br>
localValue: {{ localValue }} <br>
<input v-model="localValue">
</div>
`,
props: ['value'],
data() {
return { localValue: this.value }
},
watch: {
value () {
this.localValue = this.value
},
localValue () {
this.$emit('input', this.localValue)
}
}
})
new Vue({
el: '#app',
data: () => ({
parentValue: 'Inital value'
}),
methods: {
change () {
this.parentValue = 'Changed value'
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<my-input v-model="parentValue"></my-input>
<button @click="change">Change</button><br>
parentValue: {{ parentValue }}
</div>
I我需要这样做时总是遇到困难。
I have always faced difficulties when I need to do so.
我将非常感谢你的帮助!
I will be very grateful for the help!
推荐答案
如果您在自定义表单组件中避免使用 v-model
,则实际上只需要
If you avoid using v-model
inside your custom form component, you really only need
<b>My Input:</b> <br>
localValue: {{ value }} <br>
<input :value="value" @input="$emit('input', $event.target.value)">
否数据
,否观看
,就是这样。
参见 https://vuejs.org/v2/guide/components.html#Using-v-model-on-Components
如果你真的想要一些代表组件本地值的东西,那么Vue会赞成使用观察者的计算值(参考: https://vuejs.org/v2/guide/computed.html#Watchers )。
If you really want something representing a value local to your component, the Vue docs favour using computed values over watchers (ref: https://vuejs.org/v2/guide/computed.html#Watchers).
这里的想法是创建一个使用 getter 和 setter 计算出的值,以简化单向数据流。
The idea here is to create a computed value with getter and setter to facilitate a simplified one-way data flow.
Vue.component('my-input', {
template: `<div><b>My Input:</b> <br>localValue: {{ localValue }} <br><input v-model="localValue"></div>`,
props: ['value'],
computed: {
localValue: {
get () {
return this.value
},
set (value) {
this.$emit('input', value)
}
}
}
})
new Vue({
el: '#app',
data: () => ({
parentValue: 'Inital value'
}),
methods: {
change () {
this.parentValue = 'Changed value'
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<my-input v-model="parentValue"></my-input>
<button @click="change">Change</button><br>
parentValue: {{ parentValue }}
</div>
这篇关于子组件的v模型和子组件Vue内的v模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!