Skip to content

Instantly share code, notes, and snippets.

@blixxurd
Last active January 21, 2021 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blixxurd/b3e64fec86a3ad7d9f90b77be0654ea9 to your computer and use it in GitHub Desktop.
Save blixxurd/b3e64fec86a3ad7d9f90b77be0654ea9 to your computer and use it in GitHub Desktop.
Vue3 Store
import { reactive } from 'vue';
function ApplicationStore(app) {
const store = {
state: reactive({
// Add new store fields here
totalCents: 100,
}),
// Methods to act on the store
totalDollars() {
return parseInt(this.state.totalCents, 10) / 100;
},
setState(key, value) {
if (this.debug) {
console.log(`Attempting to set value of '${key}'='${value}`);
}
this.state[key] = value;
}
}
return store;
}
export default {
install: (app) => {
app.config.globalProperties.$store = ApplicationStore(app);
}
}
// Available app wide
// You can now use this.$store
// Properties will updates ina reactive manner
// Methods will need to be assigned to computed vars or watchers at the component level
this.$store.state.totalCents;
this.$store.totalDollars();
this.$store.setState('foo', 'bar');
import { createApp } from 'vue'
import App from '@/App.vue'
import ApplicationStore from '@/ApplicationStore';
createApp(App).use(ApplicationStore).mount('#app');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment