简体   繁体   English

孩子和父母之间共享的 v-model 值

[英]shared v-model value between child and parent

I have a component which shares v-model same as parent component.我有一个与父组件共享v-model的组件。 The code is like below:代码如下:

 Vue.component('greeting', { template: '<input type="text" :name="name" v-on:input="updateSearch($event.target.value)"> ' , props: ['name'], methods: { updateSearch: function(value) { this.$emit('input', value); } } }); const app = new Vue({ el: '#app', data: { name: '' } });
 <script src="https://unpkg.com/vue@2.6.9/dist/vue.js"></script> <div id="app"> Child: <greeting v-model="name"></greeting> <br><br><br> Main: <input type="text" v-model="name" placeholder="" /> </div>

I want to update both input boxes if the user enters text in either of them.如果用户在其中任何一个中输入文本,我想更新两个输入框。 Any suggestions would be helpful.任何的意见都将会有帮助。

Usually is a bad practice change props inside child component.通常在子组件中更改道具是一种不好的做法。 In this case, you can create two different variables and update the other one when some of them changes it value (via events and props).在这种情况下,您可以创建两个不同的变量并在其中一些变量更改其值时更新另一个变量(通过事件和道具)。

So, greeting component would $emit some event which you will catch inside main component and update main's name因此, greeting组件会 $emit 一些事件,您将在主组件中捕获并更新主组件的name

On the other hand, main component would pass a prop to greeting which will be reactive considering changes inside main and will update variable name inside greeting's data.另一方面,main 组件将传递一个 prop 给greeting ,考虑到 main 内部的变化,该 prop 将是反应性的,并将更新问候数据中的变量name

If you get more cases like that, think about using vuex如果遇到更多这样的情况,请考虑使用vuex

If you pass in a reference like an object as prop, you can bind a property of that object on both your parent and child如果您将对象之类的引用作为道具传递,则可以将该对象的属性绑定到您的父母和孩子

 Vue.component('greeting', { template: '<input type="text" v-model="name.value" />' , props: ['name'] }); const app = new Vue({ el: '#app', data: { name: { value: '' } } });
 <script src="https://unpkg.com/vue@2.6.9/dist/vue.js"></script> <div id="app"> Child: <greeting v-bind:name="name"></greeting> <br><br><br> Main: <input type="text" v-model="name.value" placeholder="" /> </div>

I think, what you are looking for is .sync modifier for events in Vue.js 2.3.0+ .我认为,您正在寻找的是 .sync Vue.js 2.3.0+ .sync事件的修饰符。

You can find a sample implementation of the same in my article here .您可以在我的文章中找到相同的示例实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM