vuexの基礎使用
1450 ワード
インストール
npm install vuex --save;
ディレクトリ構築
使用
storeの使用
npm install vuex --save;
ディレクトリ構築
-store
-store.js
使用
// store.js
import vue from 'vue'
import vuex from 'vuex'
vue.use(vuex)
export const store = new vuex.Store({
state:{
name:'abc'
},
//
getters:{
name : (state) =>{
var changeName = state.name + 'aaa'
return changeName ;
}
},
// ,
mutations:{
changeName:(state,newValue)=>{
state.name = newValue
}
},
// ; mutations
actions:{
changeNameAction:(context,newValue)=>{
setTimeout(()=>{
context.commit('changeName',newValue)
},2000)
}
}
})
storeの使用
this.$store.state.name;
this.$store.getters.name; //...mapGetters(['name'])
this.$store.commit('changeName',''tom') // mutations
this.$store.dispatch('changeName',''tom') // actions ...mapActions(['changeNameAction'])
import {mapGetters,mapMutations,mapActions} from 'vuex'
...mapGetters(['name'])
...mapMutations(['changeName'])
...mapActions(['changeNameAction']) // this.changeNameAction `this.$store.commit('changeNameAction')
...mapActions({change: 'changeNameAction') // : this.change('bbb') this.change `this.$store.commit('changeNameAction')