0
1

More than 1 year has passed since last update.

Vuexのインストール

Posted at

内容

Vue3でVuexを導入する手順。
Viteで作成しているアプリケーションに、npmで途中から導入するときの手順。
「Vite」を使用してVueプロジェクトを立ち上げる

目次

Vuexのインストール

Vue3に対応するVuexは、Ver.4以降。

npm install vuex@next

store.jsにスクリプトを記述する

プロジェクト直下にstore.jsを作成

/store.js
import { createStore } from 'vuex' // VuexのパッケージからcreateStore という関数をインポート

export const store = createStore({ // createStoreの引数にストアに関する情報をまとめたオブジェクトを指定
  state() {  // stateは、ストアに保管する値を用意しておくもの。コンポーネントのdataに相当するようなイメージ
    return { // このオブジェクトの中に、storeで利用する値をまとめておく
      message: 'This is store data.'
    }
  }
})

storeをアプリケーションに組み込む

main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import { store } from './store.js' // storeをインポート

createApp(App).use(store).mount('#app') // アプリケーションに組み込み

App.vueを修正(コンポーネントを読み込む)

App.vue
<template>
  <div id="app">
    <HelloWorld />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

storeの値を取得して画面に表示する

HelloWorld.vue
<template>
  <div class="alert alert-primary">
    <h1>{{ data.title }}</h1>
    <!-- $storeはstoreに保存している値のオブジェクト。$store.state.値 でアクセスできる -->
    <p class="mt-3 h5">{{ $store.state.message }}</p>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'

export default {
  setup(props) {
    const data = reactive({
      title: 'Vuex',
    })
    return {
      data
    }
  }
}
</script>

画面確認

npm run dev # 開発中ですでにサーバーが立ち上がっている場合は、⌃cで一度停止して再立ち上げする
0
1
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
1