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..
Vuejs uses "props" for parent/children communication and "emits" events for children/parent communication
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With