前提
「vuex state値をmounted内で使いたい」とタイトルをつけさせていただきましたが、
下記に紹介するソース・目的とするゴールが本当にvue.jsの規定に沿っているのか自体が不安と考えております、合わせてご意見をいただけましたら今後のわたくしの勉強にもなると思います、お手数ではございますがよろしくお願いいたします。
##ソース
####store/posts.js(vuexのソース)
js
export const state = () => ({ postsCategories: null }) export const getters = { postsCategories: state => state.postsCategories } export const mutations = { setPostsCategories(state, postsCategories) { state.postsCategories = postsCategories } } export const actions = { async addPostsCategory({ commit }, payload) { const newCat = {} newCat[payload.slug] = payload //console.log(newCat) await this.$axios.$patch('/postscategory.json', newCat) const postsCategories = await this.$axios.$get('/postscategory.json') //const postsCategories = await this.$axios.$get('/postscategory/' + payload.id + '.json') commit('setPostsCategories', postsCategories) }, async postsCategories({ commit }) { const postsCategories = await this.$axios.$get('/postscategory.json') commit('setPostsCategories', postsCategories) }, }
####テンプレートファイルの記述
html
<template> <section class="container posts-page"> <multiselect :selected="selected" :options="options" :multiple="true" @update="updateSelected" v-model="payload.categories" placeholder="カテゴリー選択"></multiselect > <ul> <li v-for="(cat,index) in postsCategories" :key="index">{{ cat.name }}</li> </ul> </section> </template> <script> import { mapGetters } from "vuex"; import Multiselect from "vue-multiselect"; export default { components: { Multiselect }, data() { return { selected: null, options:[] }; }, methods: { updateSelected(newSelected) { this.selected = newSelected; } }, mounted() { const cat = this.$store.state.posts.postsCategories; console.log(cat); for (var value in cat) { this.options.push(value); } }, created() { this.$store.dispatch("posts/postsCategories"); }, computed: { ...mapGetters("posts", ["postsCategories"]) } }; </script>
出来ていること
- 目的とするページに遷移をするとcreatedが作動、store/post.jsのpostsCategoriesという名のstateに格納しております。値はオブジェクトとして格納しております。
- computedのmapGettersでpostsCategoriesを getter関数として取得し、htmlにレンダリング可能です。
#実現したいこと
- multiselectという子コンポーネントにprops要素としてoptionsを設けております。渡す値をpostsCategoriesの"name"を基にした配列を入れたい。
- postsCategoriesはオブジェクトであるので配列に変換しなければならない。
- postsCategoriesの中身はこんな感じである
{ "nuxt": { "name": "Nuxt.js", "slug": "nuxt" }, "laravel": { "name": "Laravel", "slug": "laravel" }, "wp": { "name": "wordPress", "slug": "wp" }}
- mapGettersでgetterとして、postsCategoriesは取得しております、このpostsCategoriesをsetter関数として使うことはできるのか。
##試したこと
mountedにセットしようとしてみましたが、値はセットされませんでした。
mounted() { const cat = this.$store.state.posts.postsCategories; console.log(cat); for (var value in cat) { this.options.push(value); } },
上記の経験から、store.state値をどのようにsetterとして使えばよいのか、悩みだしました。
そもそもの考え方が違うのではないのかとも悩み始めております。
vue.js,vuexに詳しい方がいらっしゃいましたら、是非とも教えていただきたいです。
よろしくお願いいたします。
まだ回答がついていません
会員登録して回答してみよう