Method 1: Using a custom event
One way to update a child with fresh data from the parent is to use a custom event. To do this, the parent component can emit an event with the new data, and the child component can listen for that event and update its data accordingly.
Here is an example of how to do this: Code snippet
// Parent component
export default {
data() {
return {
data: {
// some data
}
}
},
methods: {
updateData() {
// update the data in the parent component
this.data = {
// new data
}
// emit an event with the new data
this.$emit('update', this.data)
}
}
}
// Child component
export default {
props: ['data'],
mounted() {
// listen for the update event from the parent component
this.$on('update', data => {
// update the data in the child component
this.data = data
})
}
}
Use code with caution. Learn more
Method 2: Using a prop
Another way to update a child with fresh data from the parent is to use a prop. To do this, the parent component can pass the new data as a prop to the child component, and the child component can then update its data accordingly.
Here is an example of how to do this: Code snippet
// Parent component
export default {
data() {
return {
data: {
// some data
}
}
},
methods: {
updateData() {
// update the data in the parent component
this.data = {
// new data
}
// pass the new data to the child component as a prop
this.$refs.child.setData(this.data)
}
}
}
// Child component
export default {
props: ['data'],
mounted() {
// update the data in the child component
this.setData(this.data)
}
}
Use code with caution. Learn more
Method 3: Using Vuex
Finally, you can also use Vuex to update a child with fresh data from the parent. Vuex is a state management library for VueJS that allows you to store data in a central location. This makes it easy to update data in multiple components at once.
To use Vuex to update a child with fresh data from the parent, you will need to:
Install Vuex
Create a Vuex store
Define the data that you want to share between the parent and child components in the store
In the parent component, use the store.dispatch() method to dispatch an action that will update the data in the store
In the child component, listen for the dataChanged event from the store and update its data accordingly.
Here is an example of how to do this: Code snippet
// Parent component
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
data: {
// some data
}
},
mutations: {
updateData(state, data) {
state.data = data
}
}
})
export default {
data() {
return {
data: store.state.data
}
},
methods: {
updateData() {
// update the data in the parent component
store.commit('updateData', {
// new data
})
}
}
}
// Child component
import Vue from 'vue'
export default {
mounted() {
// listen for the dataChanged event from the store
store.on('dataChanged', data => {
// update the data in the child component
this.data = data
})
}
}
Just use reactjs mate its much better.