Vue Js - Pass Data Within Two Components In The Same Level
Solution 1:
You could emit an event to parent from component1
having as parameters the updated board
and in the parent one receive that and pass it through props
to component2
In component1
:
this.$emit("sendToComp2",this.board);
in the parent
component :
<template>
<component1 @sendToComp2="sendTo2"/>
...
<component2 :boards="boards" />
....
</template>
data:{
boards:[]
},
methods:{
sendTo2(boards){
this.boards=boards
}
}
component2
should have property called boards
props:["boards"]
Solution 2:
The idea is that you have a Parent component which has at least two child components. The child components can trigger an event in the parent component and from Parent to child. So, if Component1 needs to send a message to Component2, it can trigger an event to Parent and then Parent trigger an event for Component2. Example:
<script>
export default {
name: 'Car',
methods: {
handleClick: function() {
this.$emit('clickedSomething')
}
}
}
</script>
and
<template>
<div>
<Car v-on:clickedSomething="handleClickInParent" />
<!-- or -->
<Car @clickedSomething="handleClickInParent" />
</div>
</template>
<script>
export default {
name: 'App',
methods: {
handleClickInParent: function() {
//...
}
}
}
</script>
Source: https://flaviocopes.com/vue-components-communication/
Solution 3:
You have to follow the "common ancestor pattern".
Consider the following Parent
component:
<template>
<div>
<child-one :onData="onDataFromChildOne"></child-one>
<child-two :newData="dataToChildTwo"></child-two>
</div>
</template>
<script>
export default {
name: "Parent",
data() {
return {
dataToChildTwo: null
}
},
methods: {
onDataFromChildOne(data) {
this.dataToChildTwo = data;
}
}
}
</script>
The ChildOne
component will receive a function as a prop
named onData
that should be called when the ajax call is finished. Then:
<script>
import axios from 'axios';
export default {
name: "ChildOne",
props: ['onData'],
beforeMount() {
axios
.get('/data')
.then(res => {
this.onData(res.data);
});
}
}
</script>
When onData
gets executed, dataToChildTwo
will be updated and ChildTwo
will receive the new data.
Post a Comment for "Vue Js - Pass Data Within Two Components In The Same Level"