Passing data between child components

丶灬走出姿态 提交于 2019-12-04 05:59:36
Belmin Bedak

Okay there are 2 easy ways and one more which involves the Vuex, if your app is large scale.

First way is creating the Event Bus - idea is emitting Events in one hub and then catching them where It's needed.

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

Second way is creating sort of store - plain object that would hold the state of 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 please check this VueJS access child component's data from parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!