0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vuex】ストアの作成

Posted at

はじめに

こんにちは!
今回は【Nuxt.js】ストアの作成についてアウトプットしていきます!

Vuexとは

Vuexとは、状態管理を行うためのライブラリです。アプリケーションの状態を1つの場所に置いて管理する。
(イメージ)
サーバーという夢想に広がるマンションの1室を借りて物置部屋にしている感覚。
インターネット版物置。

【メリット】
・データの流れを見えやすくすることによってバグの少ない
・デバックの少ない状態管理を実現すること。

【デメリット】
・コードが冗長になる。

【状態管理の例】
□ECサイトのショッピングカート機能
 ・最初カート内は商品が入っていない空の状態
 ・ユーザーがカートに商品を追加すると、カートに商品が入った状態になる。
 ・ユーザーが決済を行なって購入完了するとカート内は商品が入ってない状態。

【vuexの利用タイミング】
中規模から大規模のSPAを構築する場合。

ストア(store)作成

【storeとは】
各コンポーネントで共通の保管場所であるストア(store)を実装します。

storeファイルの中にindex.jsを作成します。(index.jsは決まり事)

index.js
import Vuex from 'vuex'
// ⏫vuexのインポート

// ⏬vuex.storeオブジェクトを作成して利用
const createStore = () => {
    return new Vuex.Store({
        //⏬stateに値を保管する処理 
        state: function() {
            return {
                message: 'Hello Vuex!'
            }
        }
    })
}
// ⏬作成したcreateStoreをexport defaultでexportし、使用できるようにする。
export default createStore

・vuexのインポート
・storeを作成し、stateに値を補完する処理を記述。
・エクスポート

といったことをindex.jsではやっていきます。

次にpages⏩index.vueを実装していきます。

index.vue
<template>
  <section class="container">
    <div>
          <!--⏬storeフォルダのstateの値messageを利用することができる-->
        <p>{{ $store.state.message }}</p>
    </div>
  </section>
</template>

<script>

export default {
}
</script>

<p>{{ $store.state.message }}</p>とすることでstoreフォルダのstateの値messageを利用することができるという風になります。

最後に

今回はVuex.ストアの作成についてアウトプットしました。
今回の記事を読んで質問、間違い等あればコメント等頂けると幸いです。

今後ともQiitaにてアウトプットしていきます!

最後までご愛読ありがとうございました!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?