or do we need Vuex in the end

Image for post
Image for post

You probably know Vuex when you are developing with the amazing VueJS frontend, because everybody recommends it here and there.

My first steps with Vue tries to avoid it completly, but in the end I was more or less convinced to use it. But deep in my soul I would like to get rid of it, because it feels strange with its methods, getters, using strings etc. simply unnatural.

So I was waiting for a better even simpler way to handle state in a Vue application and in the end I found one — the observable idea.

It is available in Vue.js since version 2.6.0 and very easy to use. It starts with the creation of an Observable like this.

index.js:

import vue from 'vue'
import loading from './loading'

export default loading(vue)

loading.js:

let timeoutId

const stopTimer = () => {
timeoutId && clearTimeout(timeoutId)
}

const api = (vue) => {
const state = vue.observable({
loading: undefined,
})

return {
isLoading () {
return state.loading
},
startLoading () {
stopTimer()
timeoutId = setTimeout(() => (state.loading = true), 100)
},
stopLoading () {
stopTimer()
state.loading = false
timeoutId = undefined
},
}
}

export default api

In this example I have created a loading state with timeout means when I start loading and it is done below 100 ms it will not set the state to loading otherwise we are in loading state.

The key is using Vue.observable to create a reactive object that can be used to create computed properties or simply in a template.

<template>
<v-progress-circular
v-if="loading"
class="loading"
color="info"
indeterminate
/>
</template>

<script>
import loading from '@/shared/models/loading'

export default {
computed: {
loading () {
return loading.isLoading()
}
}
}

So the question for me is, do I need anything else?

What is your opionion?

See you

Developer since the 80'th, working at Forschungszentrum Jülich (http://www.fz-juelich.de) …

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store