Vue 3: easy custom global store with computed properties
1 min readJan 20, 2021
In Vue 2 I used a global component which has been attached to the Vue object via “Vue.prototype”.
In Vue 3 there is another approach:
//store.js
import { reactive, computed } from 'vue'
const store = {
debug: true,
state: reactive({
message: 'Hello!',
val: 1,
message2: computed(() => store.state.val + 1),
}),
increment() {
this.state.val++
}
}
export {store}//main.js
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import { store } from './store'
import Axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$store = store
app.config.globalProperties.$http = Axios
app.use(router).mount('#app')//in any component
export default {
name: 'Home',
components: {
},
data() { return {
state: this.$store.state, //state is our store state
ui: {
u: true
}
}},
mounted() {
console.log(this.state)
}
}
This way, you have an easy and fast state management for small to mid size apps without the overhead when using Vuex.