Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a Vuex service
import Vue from 'vue'
import _ from 'lodash'
import { compare, stringify } from 'utils/query'
import store from 'app/store'
/**
* Car loader service
*
* Removes responsibility of loading cars from the results store
*
* @property {boolean} loading
* @property {string} query
* @property {string} lastQuery
*
* @property {Function} search
* @property {Function} load
*/
const loader = new Vue({
data () {
return {
lastQuery: '',
lastGoodState: {},
loading: false,
}
},
computed: {
state () {
return _.cloneDeep(store.get('parameters/search'))
},
query () {
return stringify(this.state)
},
},
methods: {
/**
* Search all cars
*
* @return {Promise.<TResult>}
*/
search () {
this.loading = true
return store
.dispatch('results/search')
.then(() => {
this.loading = false
})
},
/**
* Load cars based on current query
*
* @return {*}
*/
load () {
// new queries, load data
if (!compare(this.query, this.lastQuery)) {
this.lastQuery = this.query
const state = this.state
this.loading = true
return store
.dispatch('results/browse')
.then(data => {
this.loading = false
if (data.results.length) {
this.lastGoodState = state
}
return data
})
}
// same queries, return existing data
const data = _.pick(store.state.results, 'cars', 'pagination')
return Promise.resolve(data)
},
/**
* Go back to the last good state
*/
back () {
store.set('parameters/search', this.lastGoodState)
}
}
})
window.loader = loader
export default loader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.