Skip to content

Instantly share code, notes, and snippets.

@MarineLB
Created December 20, 2017 21:30
Show Gist options
  • Save MarineLB/c03c615fe491a40e5f850d03a2ff56f7 to your computer and use it in GitHub Desktop.
Save MarineLB/c03c615fe491a40e5f850d03a2ff56f7 to your computer and use it in GitHub Desktop.
vuejs vuex test - store
//creer dossier store et mettre index.js avec export default pour vuex
import Vue from 'vue';
import VueX from 'vuex';
import axios from 'axios';
Vue.use(VueX)
const getLocalStorage = () => {
let localSpecies = []
for (var i = 0; i < localStorage.length-1; i++) {
localSpecies.push(localStorage.getItem(localStorage.key(i)));
}
return localSpecies
}
const store = new VueX.Store({
state: {
species: {},
sound: true
},
getters: {
},
mutations: {
setSpecies(state, value) {
state.species = value;
},
setOneSpecie(state, ID, value) {
state.species[ID] = value;
},
setIsSaved(state, ID, value){
state.species[ID].isSaved = value
//state.commit('setLocalStorage', ID)
},
setName(state, ID, value){
state.species[ID].name = value
},
setIsFound(state, ID, value){
console.log("settingisfound")
state.species[ID].isFound = value
//state.commit('setLocalStorage', ID)
},
setGauge (state, ID, action, value) { // TODO : est-ce que cette fonction est bien placée ici? sachant qu'elle mutate pas directement une propriété mais un attribut d'une propriété
let newGaugeState = action.gauge + value
if(newGaugeState>=0 & newGaugeState <= state.species[ID].lifeGauge){
action.gauge = newGaugeState
} else if(newGaugeState<0){
action.gauge = 0
//emettre que l'animal est more ?
}else{
action.gauge = state.species[ID].lifeGauge
}
},
setLife(state, ID){
let foodGauge = state.species[ID].actions[0].gauge
let funGauge = state.species[ID].actions[1].gauge
let protectionGauge = state.species[ID].actions[2].gauge
let newLife = Math.round((foodGauge*4 + funGauge*3 + protectionGauge*3)/10)
state.species[ID].life = newLife
state.species[ID].lifePercent = (newLife/state.species[ID].lifeGauge)*100
},
setLocalStorage(state, ID){
//let localSpecies = this;
let localDatas = {};
let localSpecies = state.species[ID];
localDatas = localSpecies;
// Put the object into storage
localStorage.setItem(state.species[ID].ID, JSON.stringify(localDatas));
}
},
actions: {
getDBSpecies ({ commit, dispatch }){
axios.get('https://nautilus-api.herokuapp.com/species')
.then((res) => {
commit('setSpecies', res.data);
dispatch('getLocalSpecies');
})
.catch((err) => {
console.log('bad get'+err);
});
},
getLocalSpecies ({ commit, state }){
if(localStorage){
let dbSpecies = state.species,
localSpecies = getLocalStorage()
for (var i = 0; i < localStorage.length-1; i++) {
let localParse = JSON.parse(localSpecies[i])
if (localParse.ID === dbSpecies[localParse.ID].ID){ //avant c'était à == et pas ===
commit('setOneSpecie', localParse.ID, localParse);
}
}
}
}
}
});
export default store;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment