Search code examples
vue.jsvuejs2vue-component

Get data from one Vue single component in another component?


I use Vue.js 2.5.13 and have this structure:

component-one.vue:

    <template>
      <div>
        <input type="text" v-model="input_one">
        <component-two></component-two>
      </div>
    </template>

    <script>
      import ComponentTwo from 'component-two.vue'

      export default {
        name: "component-one",
        components: {
          ComponentTwo
        },
        data() {
          return {
            input_one: 'Hello from ComponentOne',
            input_two: ... // <-- I want to get value from ComponentTwo input_two (v-model) here
          }
        }
      }
    </script>

component-two.vue:

    <template>
      <div>
        <input type="text" v-model="input_two">
      </div>
    </template>

    <script>
      export default {
        name: "component-two",
        data() {
          return {
            input_one: 'Hello from ComponentTwo'
          }
        }
      }
    </script>

How to get data from ComponentTwo in component ComponentOne? This is important for me, because I've many similar components with fields (huge registration site form) and have no idea about calling data between Vue-components..


Solution

  • You can easily achieve this using a global event bus.

    https://alligator.io/vuejs/global-event-bus/

    For larger, more complex applications I would recommend using a state management tool such as vuex.

    https://vuex.vuejs.org/en/