Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 259
koddr Avatar asked Jan 29 '18 11:01

koddr


1 Answers

Vuejs uses "props" for parent/children communication and "emits" events for children/parent communication

enter image description here

You have to remember that for every prop you pass to the child component you should add that prop to the props array. The same applies to events: every events you emit you should be caught in the parent component, like so:

component-one.vue:

    <template>
      <div>
        <input type="text" v-model="input_one">
        <component-two
            @CustomEventInputChanged="doSomenthing">
        </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: ''
          }
        },
        methods: {
            doSomenthing ( data ) {
                this.input_two = data;
            }
        }
      }
    </script>

component-two.vue:

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

    <script>
      export default {
        name: "component-two",
        data() {
          return {
            input_one: 'Hello from ComponentTwo'
          }
        },
        methods: {
            emitEventChanged () {
                this.$emit('CustomEventInputChanged', this.input_two);
            }
        }

      }
    </script>

This should work

like image 88
Luca Giardina Avatar answered Oct 02 '22 20:10

Luca Giardina