Utilizing a data attribute, referred to as data
in this specific example, allows for the creation of a basic store using reactive
. This store can then be imported and utilized by sibling components (Component A and B).
// store.js
import { reactive } from 'vue'
export const store = reactive({
data: 'New Message',
setData(something) {
this.data = something;
},
})
<!-- ComponentA.vue -->
<script>
import { store } from './store.js'
export default {
data() {
return {
store
}
}
}
</script>
<template>From A: {{ store.data }}</template>
Additionally,
<!-- ComponentB.vue -->
<script>
import { store } from './store.js'
export default {
data() {
return {
store
}
},
watch: {
// To trigger an event upon change:
'store.data'(newData, oldData) {
console.log('Data Changed', { newData, oldData });
}
},
}
</script>
<template>From B: {{ store.data }}</template>
Updates to the state within the store will automatically propagate to all child components that utilize it. This method provides a simpler alternative to Vue 2's $emit
approach, eliminating the need to manually trace events throughout the component hierarchy.