Transferring data between child components

I fight for it to work. I need to access the selected value in a SelectLangComponent element from a FormComponent. Is there any direct way to do this, or should we pass it from the parent component (act like the average person)? I already tried with $emit on SelectLangComponent and v-on:.. on FormComponent, but it didn't work.

ChooseLangComponent:

 <template lang="html"> <div class="choose-lang"> <select v-model="selected"> <option v-for="lang in langs" v-bind:value="lang.value">{{lang.text}}</option> </select> </div> </template> <script> export default { data() { return { selected: 'en', langs: [ { text: 'English', value: 'en' }, { text: 'German', value: 'ge' }, ] } } } </script> 

FormComponent:

 <template lang="html"> <div class="form-name"> <div class="inputs"> <input type="text" v-model="nameText" v-on:keyup.enter="send_name"> </div> </div> </template> export default { data() { return { nameText: '', } }, methods: { send_name() { // I need the selected language here } } } 

Parent component:

 <div id="app"> <choose-lang></choose-lang> ... <form-comp></form-comp> </div> ... Vue.component('choose-lang', require('./components/ChooseLangComponent.vue')); Vue.component('form-comp', require('./components/FormComponent.vue')); const app = new Vue({ el: '#app', data: { ... }); 
+5
source share
1 answer

Well, there are 2 easy ways, and one more that includes Vuex if your application is large-scale.

The first way to create an Event Bus is to emit events in a single hub, and then catch them where necessary.

 const Bus = new Vue({}) Vue.component('lang', { template: '#lang-tmp', data() { return { selected: 'en', langs: [ { text: 'English', value: 'en' }, { text: 'German', value: 'ge' }, ] } }, created() { this.changeLang() }, methods: { changeLang() { Bus.$emit('langChanged', this.selected) } } }) Vue.component('frm', { template: '#frm-tmp', data() { return { selectedItem: 'en' } }, created() { Bus.$on('langChanged', (selected) => { this.selectedItem = selected }) } }) const app = new Vue({ el: '#app' }) 

http://jsbin.com/siyipuboki/edit?html,js,output

The second way is to create a view of the store - a simple object that will hold the state of the selected item

 const store = { data: { selected: null } } Vue.component('lang', { template: '#lang-tmp', data() { return { selected: 'en', langs: [ { text: 'English', value: 'en' }, { text: 'German', value: 'ge' }, ] } }, created() { this.changeLang() }, methods: { changeLang() { store.data.selected = this.selected } } }) Vue.component('frm', { template: '#frm-tmp', data() { return { storeSelected: store.data } } }) const app = new Vue({ el: '#app' }) 

http://jsbin.com/qagahabile/edit?html,js,output

Also check the VueJS child component data from the parent

+7
source

Source: https://habr.com/ru/post/1266198/


All Articles