Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScriptで Vueを書いてみよう!

jiko21
June 22, 2019

TypeScriptで Vueを書いてみよう!

v-kansai Vue.js/Nuxt.js meetup #7の登壇資料です

jiko21

June 22, 2019
Tweet

More Decks by jiko21

Other Decks in Technology

Transcript

  1. 型が使えてうれしいこと… • JSだとこのまま実⾏されてしまう。 • 予期せぬバグの原因に • ちなみに… • add(a,b) ->

    11 (string型) • mul(a,b) -> 1 (number型) function add (a, b) { return a + b; } function mul (a, b) { return a * b; } const a = 1; const b = “1"; add(a, b); mul(a, b);
  2. TSだとこう書ける! • トランスパイルの段階で はじかれるし、 VS Codeとかだと、書くだけで 怒られる function add(a: number,

    b: number): number { return a + b; } function mul(a: number, b: number): number { return a * b; } const a = 1; const b = "1"; console.log(add(a, b)); console.log(mul(a, b));
  3. JSDocとの違い • JSDocは何回も書く必要あり? • TSなら⼀度どっかに書いとけばそれをimportするだけでいい • entities/*.tsとか、models/*.tsとか /** * @param

    todo TODO Entity Object * @param {string} todo.content actual task * @param {number} todo.status status: {todo->0, doing->1, done->2} * @param {string} todo.key firebase key */ export default interface Todo { content: string; status: number; key: string; }
  4. Class Style Componentって? import Vue from 'vue'; import {mapGetters, mapActions,

    mapState} from 'vuex'; export default Vue.extend({ name: 'Header’, props: { isToggled: { type: Boolean, required: true, }, doLogout: { type: Function, required: true, }, toggleBurger: { type: Function, required: true, }, }, computed: { ...mapGetters( ['isLoggedIn’], ), }, }); 普通に書いた場合 (Object Style)
  5. Class Style Componentって? import {Component, Prop, Vue} from "vue-property-decorator"; import

    {mapGetters, mapActions, mapState} from 'vuex'; @Component({ computed: { ...mapGetters( ['isLoggedIn’], ), }, }) export default class Header extends Vue { @Prop() private isToggled!:boolean; @Prop() private doLogout!:() => {}; @Prop() private toggleBurger!:() => {}; } 型周りはきれい
  6. Actions • VueからActionを受け取る部分 • この中にどんどんactionを定義していく const actions: ActionTree<TopState, RootState> =

    {... initialize({ commit }) { const user = this.state.user; if (user !== null) { firebaseRdbService.getTodos(user, (todos: TodoResponse|null) => { if (todos !== null) { commit('setTodos', objModule.objectToArrayWithKey(todos!)); } }); } },
  7. Mutations • めっちゃかんたん • ここでも引数に型、つけられます! const mutations: MutationTree<TopState> = {...

    const mutations: MutationTree<TopState> = { setTodos(state: TopState, todos: Todo[]): void { state.todos = todos; }, };
  8. Getters • これもかんたん! • 普通のTypeScriptですよね… const getters: GetterTree<TopState, RootState> =

    {... const getters: GetterTree<TopState, RootState> = { getAllTodos(state: TopState): TodoPacks|null { return { todo: filterTodos(state.todos, 0), doing: filterTodos(state.todos, 1), done: filterTodos(state.todos, 2), }; }, ...