Skip to content

Instantly share code, notes, and snippets.

@chickenfoot88
Forked from lmiller1990/App.vue
Created June 27, 2019 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chickenfoot88/c634f0f63bf3ef92e491ce30d9f13127 to your computer and use it in GitHub Desktop.
Save chickenfoot88/c634f0f63bf3ef92e491ce30d9f13127 to your computer and use it in GitHub Desktop.
<template>
<div id="app">
<p>
Pending: {{ $store.state.getInfoPending }}
</p>
<p>
{{ $store.state.getInfoData }}
</p>
</div>
</template>
<script>
export default {
created () {
this.$store.dispatch('getAsync')
}
}
</script>
import axios from 'axios'
const doAsync = (store, { url, mutationTypes, stateKey }) => {
store.commit(mutationTypes.PENDING)
setTimeout(() => {
axios(url, {})
.then(response => {
store.commit(mutationTypes.SUCCESS, response.data)
})
.catch(error => {
store.commit(mutationTypes.FAILURE)
})
}, 1500)
}
export default doAsync
/* To run this gist, make an app using the vue-cli and webpack-simple template.
* vue init webpack-simple some-app
* also you will need to `yarn add axios vuex lodash --save`
*/
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
import _ from 'lodash'
const createAsyncMutation = (type) => ({
SUCCESS: `${type}_SUCCESS`,
FAILURE: `${type}_FAILURE`,
PENDING: `${type}_PENDING`,
loadingKey: _.camelCase(`${type}_PENDING`),
stateKey: _.camelCase(`${type}_DATA`)
})
export const GET_INFO_ASYNC = createAsyncMutation('GET_INFO')
import Vue from 'vue'
import Vuex from 'vuex'
import doAsync from './async-util'
import * as types from './mutation-types'
Vue.use(Vuex)
const mutationTypes = {
SUCCESS: 'GET_INFO_SUCCESS',
FAILURE: 'GET_INFO_FAILURE',
PENDING: 'GET_INFO_PENDING'
}
const state = {
info: {},
}
const mutations = {
[types.GET_INFO_ASYNC.SUCCESS] (state, info) {
state[types.GET_INFO_ASYNC.loadingKey] = false
Vue.set(state, [types.GET_INFO_ASYNC.stateKey], info)
},
[types.GET_INFO_ASYNC.PENDING] (state) {
console.log(types.GET_INFO_ASYNC.loadingKey)
Vue.set(state, types.GET_INFO_ASYNC.loadingKey, true)
}
}
const actions = {
getAsync(store) {
doAsync(store, {
url: 'https://jsonplaceholder.typicode.com/posts/1',
mutationTypes: types.GET_INFO_ASYNC
})
}
}
export default new Vuex.Store({
state,
mutations,
actions
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment