Last active
January 21, 2021 18:23
-
-
Save blixxurd/b3e64fec86a3ad7d9f90b77be0654ea9 to your computer and use it in GitHub Desktop.
Vue3 Store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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