vuexの詳細
Vuexの概要
Vuexの基本的な使用
1.vuex依存パッケージのインストール
2.srcファイルにstoreフォルダを新規作成し、indexを新規作成します.jsファイル
3.main.js storeオブジェクトをvueインスタンスにマウント
Vuexのコアコンセプト State
Stateは唯一の共通データソースを提供し、すべての共有データをStoreに統合して格納する Mutation
Storeのデータ1を変更するために使用する.Storeデータはmutationでしか変更できず、Storeのデータを直接操作することはできない.このように操作するのは少し面倒ですが、すべてのデータの変化を集中的に監視することができます. Action
Actions非同期タスクのトリガー時にパラメータを携帯 Getter
Getterは、Storeのデータを加工処理する新しいデータ1を形成するために用いる.Getterは、Storeにもあるデータを加工処理して新しいデータ、タイプVueの計算属性2を形成することができる.Storeのデータが変わり、Getterのデータも変わります
コンポーネントがStateデータにアクセスする2つの方法第1種 第2種
コンポーネントがStateデータを変更する2つの方法第1種 第2種
コンポーネントがStateデータを非同期で変更する2つの方法第1種 第2種
コンポーネントがStateデータにアクセスする2つの方法第1種 第2種
Vuexのケース
詳しく説明する
Vuex
はコンポーネントのグローバル状態(データ)管理を実現するメカニズムであり、コンポーネント間のデータの共有を容易に実現することができる.Vuexの基本的な使用
1.vuex依存パッケージのインストール
npm install vuex --save
2.srcファイルにstoreフォルダを新規作成し、indexを新規作成します.jsファイル
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
}
const getters = {
}
const mutations = {
}
const actions = {
}
const store = new Vuex.Store({
state,
getters,
mutations,
actions
})
// store
export default store
3.main.js storeオブジェクトをvueインスタンスにマウント
import store from './store' // store
new Vue ({
el: '#app',
render: h => h(app),
// , Vue
// , store
store
})
Vuexのコアコンセプト
Stateは唯一の共通データソースを提供し、すべての共有データをStoreに統合して格納する
const store = new Vuex.Store({
state: {
count: 0
}
})
Storeのデータ1を変更するために使用する.Storeデータはmutationでしか変更できず、Storeのデータを直接操作することはできない.このように操作するのは少し面倒ですが、すべてのデータの変化を集中的に監視することができます.
// Mutation
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state, step) {
//
state.count += step
}
}
})
Actions非同期タスクのトリガー時にパラメータを携帯
// Action
const strore = new Vuex.Store({
mutation: {
add(state, step) {
state.count += step
}
},
actions: {
addAsync(context, step) {
setTimeout(() => {
context.commit('add', step)
}, 1000)
}
}
})
Getterは、Storeのデータを加工処理する新しいデータ1を形成するために用いる.Getterは、Storeにもあるデータを加工処理して新しいデータ、タイプVueの計算属性2を形成することができる.Storeのデータが変わり、Getterのデータも変わります
Getter
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showNum: state => {
return: ' '+statecount
}
}
})
コンポーネントがStateデータにアクセスする2つの方法
this.$store.state.
// vuex mapState
import { mapState } from 'vuex'
// mapState , , computed
computed: {
...mapState({'count'})
}
コンポーネントがStateデータを変更する2つの方法
this.$store.commit.('add',3)
// vuex mapState
import { mapMutations } from 'vuex'
// mapMutations , mutations , methods
methods: {
...mapMutations(['add'])
this.add(3);
}
コンポーネントがStateデータを非同期で変更する2つの方法
this.$store.dispatch('add', 3)
// vuex mapState
import { mapActions } from 'vuex'
// mapActions , actions , methods
methods: {
...mapActions(['addAsync'])
this.addAsync(3);
}
コンポーネントがStateデータにアクセスする2つの方法
this.$store.getters.
// vuex mapState
import { mapGetters } from 'vuex'
// mapActions , actions , methods
computed: {
...mapGetters(['shouNum'])
this.mapGetters();
}
Vuexのケース
詳しく説明する