Last active
March 19, 2021 17:05
-
-
Save james2doyle/de062f26764fed284eeebd20473c1c5a to your computer and use it in GitHub Desktop.
A reactive datastore using lodash as the backend
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/reactivity'; | |
import lodash from 'lodash'; | |
const defaultState = { | |
count: 1 | |
}; | |
/** | |
* Create a database that is reactive | |
*/ | |
const makeDb = (state = {}) => { | |
const store = reactive(state); | |
return lodash.chain(store); | |
}; | |
export default makeDb({ state: defaultState }); |
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
<template> | |
<button @click.prevent="updateCount">count is: {{ count }}</button> | |
</template> | |
<script setup> | |
import { ref, watchEffect } from 'vue'; | |
import db from 'lodash-reactive-store.js'; | |
const counter = db.get('state.count'); | |
const count = ref(counter.value()); | |
const updateCount = () => { | |
// must call `.value()` to trigger the effect | |
db.set('state.count', count.value + 1).value(); | |
} | |
// runs on updates of the db state | |
watchEffect(() => { | |
// fetch the fresh value from the db state | |
count.value = counter.value(); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment