4
4

More than 3 years have passed since last update.

TypeScriptでVuex,Vueをめちゃくちゃ楽に使う

Last updated at Posted at 2019-09-27

記事を書いた経緯

新卒で配属された入門プロジェクトとしてツールを作ることになり、
そこで初めてVueを使うことになりました。

VueのチュートリアルもそこそこにVuexとかTypeScriptとかつかって
色々過程をすっとばして作っていきました。

Vuexとは

この記事を読んでくれている人は、もう知っている人が多いと思いますが、
Vueのための状態管理ができる便利なライブラリです。

Vueの特徴の一つに単一コンポーネントを用いた開発があります。
その際にコンポーネント間での値の受け渡しで結構苦戦しました。

これを解決してくれるのが、このVuexです。

アプリケーション全体の状態をこのVuexで管理することで値の共有を容易にします。

Vuexを便利に使うためのライブラリ

今回の主題でもありますが、Vuexを簡単に使えたライブラリがありますそれが、

vuex-classです。

このvuex-classは使用するコンポーネント内で@丸々のデコレーターをつけるだけで
それぞれの状態を呼び出すことができます。

よく使うstateの値とactionの実行をやってみるサンプルだけ置いておきます。

説明は省きますが、自分が使っているもう一つのライブラリはこちら(vue-property-decorator)

サンプル

store.ts
import Vuex from 'vuex';
import Vue from 'vue';

Vue.use(Vuex);

interface StateInterface {
  text: string | null;
}
export default new Vuex.Store({
  state: {
    text: "a"
  } as StateInterface,
  mutations: {
    setText(state, text) {
      state.text = text;
   }
  },
 actions: {
  changeText({ state, commit }) {
   commit('setText', "b");
  }
 }
})
sample.vue
<template>
 <div>{{text}}</div>
 <button :click="changeText()">change</button>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { Action, Getter, State } from 'vuex-class';

@Component
export default class Sample extends Vue {
@State
private text!: string;

@Action
private changeText!: () => void;
}
</script>
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4