52.【vue3】—— (6)vuex(vue2、vue3对比)(2024-03-20)

 vue2.x中的vuex版本是4.x以下,vue3.x中使用的vuex版本必须保证在4.x以上

1.state

(1)this.$store.state.全局数据名称

(2)mapState(computed)

import {mapState} from 'vuex'

computed:{

...mapState(['全局数据1'])  //['全局数据2','全局数据2']

}

然后就可以不用$store.state.全局数据引用,直接插值{{全局数据}}



2.getters

例:

getters:{

数据名称(state){

return  state.state中定义的数据+1

}

}

(1)this.$store.getters.数据名称

(2)mapGetters(computed)

import {mapGetters} from 'vuex'

computed:{

...mapGetters([数据名称])

}

然后就可以直接插值{{数据名称}}


3.mutations

(1)this.$store.commit()


mutations:{

 addN(state,step){

state.count+=step

 }

}


this.$store.commit('addN',3)

(2)mapMutations(methods)


import {mapMutations} from 'vue'

methods:{

...mapMutations(['addN'])

}

在需要的的地方直接使用this.add(3)


4.actions

(1)this.$store.dispatch()

actions:{

addNAsync(context,step){

setTimeout(()=>{

context.commit('addN',step)

},1000)

}

}

this.$store.dispatch('addNAsync',+5)

(2)mapActions(methods)

import {mapActions} from 'vuex'

methods:{

...mapActions(['addNAsync'])

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vuex是vue中的一种状态管理模式,就是一个 状态仓库,仓库做什么?存储状态、管理状态(数据)的变化、提供状态获...
    杨_4d81阅读 1,670评论 0 0
  • #vue2笔记 ##脚手架文件结构 ├──node_modules ├──public │├──favicon.i...
    Daydream_许多阅读 3,251评论 0 0
  • 刚开始接触uniApp看了一下vuex的使用方法,总结一下在项目中个人认为常用的架构,很实用,做一个新手学习笔记!...
    翟小乙阅读 11,035评论 0 1
  • Vuex 作用:管理多个组件或者全局共享的状态。将复杂的、需要共享的逻辑处理放入actions中共享。 ( 为什么...
    恒星的背影阅读 3,633评论 0 0
  • 笔记 脚手架文件结构 关于不同版本的Vue vue.js与vue.runtime.xxx.js的区别:vue.js...
    sskingfly阅读 1,007评论 0 0