Last active
December 6, 2018 16:01
-
-
Save potato4d/691f775e834623aa3fa5ceb29cc6093a to your computer and use it in GitHub Desktop.
Vuex に雑に最低限の型をつけたいときに使うやつ
This file contains hidden or 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> | |
<div> | |
<p>{{count}}</p> | |
<button type="button" @click="increment">+</button> | |
</div> | |
</template> | |
<script lang="ts"> | |
import Vue from 'vue' | |
export default Vue.extend({ | |
computed: { | |
count() { | |
return this.$state.count // これは補完が効く | |
}, | |
anyCount() { | |
return this.$store.state.count // これは any | |
} | |
}, | |
methods: { | |
increment() { | |
this.$store.dispatch('increment') // ここの ActionTypes は定義しているわけではないので any | |
// keyof にしてやればいけるので、やりたかったら shims-vue.d.ts を編集する | |
} | |
} | |
}) | |
</script> |
This file contains hidden or 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 Vue from 'vue' | |
import Vuex from 'vuex' | |
Vue.use(Vuex) | |
export interface State { | |
count: number | |
} | |
export interface Context { | |
commit: (name: string) => void | |
} | |
export interface Mutations { | |
[key of string]: (state: State, payload?: any) => void | |
} | |
export interface Actions { | |
[key of string]: (context: Context, payload?: any) => void | |
} | |
export const state: State = { | |
count: 0 | |
} | |
export const mutations: Mutations = { | |
increment(state) { | |
state.count ++ | |
} | |
} | |
export const actions: Actions = { | |
increment({ commit }) { | |
commit('increment') | |
} | |
} | |
export default new Vuex.Store({ | |
state, | |
mutations, | |
actions | |
}) |
This file contains hidden or 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 Vue from 'vue' | |
import * as Vuex from 'vuex' | |
import * as CustomStore from '../store/' | |
declare module 'vue/types/vue' { | |
interface Vue { | |
$store: Vuex.Store<any>, // ここがちょうどいま問題になってるやつ | |
$state: State | |
} | |
} | |
/** | |
本当はこうしたい……こうしたくない? | |
interface ICustomStore extends Vuex.Store { | |
state: CustomStore.State | |
dispatch: (k: keyof CustomStore.actions) => any | |
} | |
interface Vue { | |
$store: ICustomStore | |
} | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment