vuexのコンポーネント間のデータ受け渡し方法
vuexのデータの受け渡しはvuexのドキュメントを読めばだいたいのことがわかる。
vuexはVue.js アプリケーションのための 状態管理パターン + ライブラリである。
重要なファイル 最初はApp.vueとstore/index.jsだけで済む。
<template> <v-app> <v-app-bar app color="primary" dark > <div class="d-flex align-center"> <v-img alt="Vuetify Logo" class="shrink mr-2" contain src="https://cdn.vuetifyjs.com/images/logos/vuetify-logo-dark.png" transition="scale-transition" width="40" /> <v-img alt="Vuetify Name" class="shrink mt-1 hidden-sm-and-down" contain min-width="100" src="https://cdn.vuetifyjs.com/images/logos/vuetify-name-dark.png" width="100" /> </div> <v-spacer></v-spacer> <v-btn href="https://github.com/vuetifyjs/vuetify/releases/latest" target="_blank" text > <span class="mr-2">Latest Release</span> <v-icon>mdi-open-in-new</v-icon> </v-btn> </v-app-bar> <v-content> <HelloWorld/> </v-content> <form> <input type="text" v-on:input="updateMessage" ><br /> <button>submit</button> </form> <span>{{ obj }}</span> </v-app> </template> <script> import { mapState } from 'vuex' import HelloWorld from './components/HelloWorld'; export default { name: 'App', components: { HelloWorld, }, data: () => ({ // }), methods:{ updateMessage: function(e){ console.log("update") this.$store.dispatch('updateTest', {message: e.target.value}) } }, computed:{ ...mapState({ obj: state => state.obj }) } }; </script>
どのようにstateにデータを保存するか。これはmethodsにupdateMessageメソッドが存在する。
this.$store.dispatch('updateTest', {message: e.target.value})
this.$store.dispatch()はactionsを呼び出す。第一引数の文字列はstore/index.jsのうちactionsに含まれているもののうち何のプロパティを呼び出すかを示している。
また第2引数は{message: e.target.value}みたいな感じで渡さないとstore/index.jsでデータをきちんと受け取ってくれない現象に陥る。(具体的にはundefinedになる。)
そしてこのメソッドはtemplateタグ内のinputタグでv-on:inputメソッドの引数として使われている。
入力される-> this.$store.dispatch()でupdateTestが実行される。
また基本的にstateのデータはcomputedを通じてstateのデータを取得するようだ。
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { obj: "hhh" }, mutations: { updateMessage (state, message) { state.obj = message } }, actions: { updateTest: function({commit}, {message}){ commit("updateMessage", message) } }, modules: { } })
このファイルはvuexのデータフローの仕組みをまとめるものである。actionsで何かが呼ばれればcommitによってmutationsが呼ばれる。mutationsによってstateの内容を変更する。こんな感じの流れになっている。