优秀的编程知识分享平台

网站首页 > 技术文章 正文

Vue组件开发之Vuex详细使用(vuex如何调用组件方法)

nanyue 2024-09-29 15:09:08 技术文章 187 ℃

Vuex的state

State 提供唯一公共数据源,所有共享数据都要统一放到store的state中存储

const store = new Vuex.Store({
  State: {count: 0}
})
组件访问state的第一种方式
this.$store.state.count
组件访问state的第二种方式
从vuex中按需导入mapState函数
import { mapState } from ‘vuex’

通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为computed属性
computed: {
 ...mapState([‘count’])
}

Vuex的mutation

Mutation 用于变更store中的数据,不可以在其他组件直接操作store中数据

const store = new Vuex.Store({
  state: { count: 0
},
mutations: {                          //变更数据的操作,操作state中数据
    																				//事件处理函数
}
})
触发mutation,在组件中调用
methods: {
  函数名(){
  this.$store.commit(‘mutation的事件处理函数名’)     //commit()调用mutation参数
}
}

在定义mutation是可以传递参数

mutations: {
  addN(state,step) {          //定义addN函数,state是默认参数,step自定义参数
   state.count += step
}
}
//组件调用mutations函数
methods: {
  handle2(){
  this.$store.commit(‘addN’,3)   //3就是传入的step的实际参数
}
}

访问mutations的第二种方法

从vuex中按需导入mapMutations函数
import { mapState,mapMutations } from ‘vuex’
将指定的mutations函数,映射为当前组件的methods函数
methods: {
  ... mapMutations ([‘add’, ‘addN’])
  //函数方法
  this.add()
  this.addN()
}

vuex的action

action用于处理异步任务

如果通过异步操作变更数据,必须通过action,而不能使用mutation,但是在action中还是要通过触发mutation的方式间接变更数据

const store = new Vuex.Store({
  state: {count: 0
},
mutations: {                          
addN(state,step) {
  state.count +=step
}
},
actions: {
  addNAsync(context,step) {
    setTimeout(() => {
     context.commit(‘addN’, step)
})
}
}
})
触发action,在组件中调用
methods: {
  handle(){
  this.$store.dispatch(‘addNAsync’,5)     //dispatch()调用异步操作函数
}
}
组件调用action的第二种方式
import { mapState,mapMutations,mapActions} from ‘vuex’    //按需导入mapActions
methods: {
  ... mapActions ([‘addNAsync’])
  //调用
  this. addNAsync()
}

vuex的getter

getter用于对store中的数据进行加工处理形成新的数据

  • getter对源数据加工处理,类似vue的计算属性
  • store数据发生变化,getter数据也会发生变化
const store = new Vuex.Store({
  state: {
   count: 0
},
  getters: {
   showNum: state => {
   return ‘当前最新数据量是【‘+state.count+’】’
}
}
})

Tags:

最近发表
标签列表