LoginSignup
1
1

More than 3 years have passed since last update.

Vuex用語整理(個人メモ)

Last updated at Posted at 2020-08-20

目的

nuxt.jsでVuexでデータを扱いたいときに、すぐに忘れてしまうためメモとして残しておきたい

参考リンク

https://reffect.co.jp/vue/understaind-vue-basic
https://ja.nuxtjs.org/guide/vuex-store/

基礎

なぜ使うと便利?

複数コンポーネントからデータを一元管理するときにpropsやemitから解放されるためvueファイル内のdataプロパティで扱うより容易になるケースがある。

$store

データを格納する場所

export const state = () => ({
  name: value
})

getters

computedプロパティと同じ。複数コンポーネントでフィルターの条件など使いまわせる分DRYになる

export const getters = () => ({
  getValue(state) {
    return state.value
  },
})

使い方

return this.$store.getters.getValue;

mutations

stateの中身を編集することだけに使う。それ以外の複雑な処理はactionsに記述

export const mutations = {
  changeState(state) {
    state.value = ??
  },
}

使うときはcommitを使う。

methods: {
  chnageState(){
    this.$store.commit('chnageState')
  }
 },

payloadでmutationに引数を渡す。

export const mutations = {
  chnageState(state, payload) {
    state.value = state.value = payload
  },
}
methods: {
  changeState() {
    this.$store.commit('chnageState', 'value')
  },
},

actions

mutationsを経由してcommitする。非同期処理が可能。

export const actions = {
  changeStateAction(context) {
    context.commit('chnageStateActoin')
  }
}

// or (context内でcommitしか使わない場合)

export const actions = {
  changeStateAction({commit}) {
    commit('chnageStateActoin')
  }
}

contextというstoreインスタンスが引数に入る

実行するには

methods: {
  changeStateAction() {
    this.$store.dispatch('chnageStateAction')
  },
},

非同期処理を書くには(axios)

export const state = () => ({
  data: [],
})

export const mutations = {
    setData(state, data) {
        state.data = data
    }
}

export const actions = {
  getData({commit}) {
    return axios.get(url).then(res => {
        commit('setData', res.data)
    })
  }
}

つかうときは

this.$store.dispatch('getData')
1
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
1
1