Skip to content

Instantly share code, notes, and snippets.

@botmaster
Created March 3, 2022 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save botmaster/adc54cc0d96712c916db3fb92514d906 to your computer and use it in GitHub Desktop.
Save botmaster/adc54cc0d96712c916db3fb92514d906 to your computer and use it in GitHub Desktop.
Basic Vuex setup
// State object
const state = {
variable1: 0,
variable2: 'value2',
variable3: 'value3',
_internalTimeout: null,
isLoading: false,
hasError: false,
}
// Getter functions
const getters = {
getVariable1( state ) {
return state.variable1
},
getVariable2( state ) {
return state.variable2
}
}
// Actions
const actions = {
fetchVariable1({ state, commit }) {
commit('REQUEST_VARIABLE_1')
setTimeout(() =>{
if(Math.random() >= 0.4 ) {
commit('RECEIVE_VARIABLE_1_SUCCESS', 1)
} else {
commit('RECEIVE_VARIABLE_1_FAILED', 'oups')
}
}, 1599)
}
}
// Mutations
const mutations = {
REQUEST_VARIABLE_1(state) {
state.isLoading = true
state.hasError = false
},
RECEIVE_VARIABLE_1_SUCCESS(state, data) {
state.variable1 += data
state.isLoading = false
state.hasError = false
},
RECEIVE_VARIABLE_1_FAILED(state, error) {
state.isLoading = false
state.hasError = error
},
SET_VARIABLE_2(state, data) {
state.variable2 = data
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
<template>
<div>
<h3>Vuex tests</h3>
<p class="font-bold">
State
</p>
<p>isLoading: {{ isLoading }}</p>
<p>hasError: {{ hasError }}</p>
<p class="font-bold">
Getters
</p>
<p>getVariable1: {{ getVariable1 }}</p>
<p>getVariable2: {{ getVariable2 }}</p>
<p class="mt-10 font-bold">
Actions
</p>
<p>
<button :disabled="isLoading" class="btn" @click="btnCLickHandler">
Fetch variable 1
</button>
</p>
<p v-if="hasError">
Error: {{ hasError }}
</p>
<p v-else-if="isLoading">
Loading...
</p>
<p v-else>
variable1: {{ variable1 }}
</p>
</div>
</template>
<script>
import { mapGetters, mapState } from 'vuex'
export default {
name: 'CalendarComponent',
computed: {
// mix the getters into computed with object spread operator
...mapGetters('scheduler', [
'getVariable1',
'getVariable2',
]),
...mapState('scheduler',[
// map this.count to store.state.count
'variable1',
'hasError',
'isLoading'
]),
},
methods: {
btnCLickHandler() {
this.$store.dispatch('scheduler/fetchVariable1')
}
},
}
</script>
<style scoped>
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment