使用vuex管理数据

src/vuex/store.js

 

组件里面使用引入store.js,注意路径

import store from 'store.js'

然后在使用的组件内data(){}同级放入store

 

三大常用的方法state,mutations,getters

 

重要的一步,当把state,mutation,getter写完之后,需要向外暴露接口

const store=new Vuex.Store({
state,

mutations,
getters
})

export default store

 

 

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

//管理的数据,存储起来

var state={
num:1
}

 

若外边的组件想用这个值,this.$store.state.num

 

方法,可以在组件里面事件引用

var mutations={
inc:function(){
++state.num
}
}

 

例如 <button @click="changeState"></button>,用组件里的事件映射store里面的事件

changeNum:function(){
this.$store.commit('inc')
}

 

getters方法类似于mounted计算属性

var getters={
computedNum:function(state){
return state.num*2
}
}

组件里面的视图更新执行方法

{{this.$store.getters.computedNum}}

 

 

最后,分清他们的用途,就可以愉快使用vuex了

 

posted @ 2018-05-30 21:27  斯丢皮德曼  阅读(218)  评论(0编辑  收藏  举报