-
-
Save hoangmirs/e0fa685476344dc274d5c34a183d1547 to your computer and use it in GitHub Desktop.
Share mutations store plugin
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 LS from '@/utilities/LocalStorage'; | |
export default ({ paths }) => (store) => { | |
let committingMutation = []; | |
store.subscribe((mutation) => { | |
committingMutation = LS.get('committingMutation') || []; | |
const mutationType = mutation.type; | |
if (committingMutation.indexOf(mutationType) !== -1) return; | |
if (paths.indexOf(mutationType) !== -1) { | |
LS.set(mutationType, mutation.payload); | |
committingMutation.push(mutationType); | |
LS.set('committingMutation', committingMutation); | |
} | |
}); | |
window.onfocus = () => { | |
committingMutation = LS.get('committingMutation') || []; | |
committingMutation.forEach((mutationType) => { | |
if (paths.indexOf(mutationType) !== -1) { | |
try { | |
const payload = LS.get(mutationType); | |
if (payload) { | |
store.commit(mutationType, payload); | |
} | |
} catch (error) { | |
console.error('[vuex-shared-mutations] Unable to parse shared mutation data'); // eslint-disable-line | |
console.error(event.newValue, error); // eslint-disable-line | |
} finally { | |
const index = committingMutation.indexOf(mutationType); | |
if (index > -1) { | |
committingMutation.splice(index, 1); | |
LS.set('committingMutation', committingMutation); | |
LS.remove(mutationType); | |
} | |
} | |
} | |
}); | |
}; | |
window.addEventListener('storage', (event) => { | |
if (event !== 2) return; | |
if (event.newValue === null) return; | |
const mutationType = event.key; | |
if (paths.indexOf(mutationType) !== -1) { | |
try { | |
committingMutation = LS.get('committingMutation') || []; | |
if (committingMutation.indexOf(mutationType) === -1) { | |
committingMutation.push(mutationType); | |
LS.set('committingMutation', committingMutation); | |
} | |
const payload = LS.get(mutationType); | |
if (payload) { | |
store.commit(mutationType, payload); | |
} | |
} catch (error) { | |
console.error('[vuex-shared-mutations] Unable to parse shared mutation data'); // eslint-disable-line | |
console.error(event.newValue, error); // eslint-disable-line | |
} finally { | |
setTimeout(() => { | |
const index = committingMutation.indexOf(mutationType); | |
if (index > -1) { | |
committingMutation.splice(index, 1); | |
LS.set('committingMutation', committingMutation); | |
LS.remove(mutationType); | |
} | |
}, 1000); | |
} | |
} | |
}, false); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment