官方文档 Mutation | Vuex

在vue3中使用vuex 4.x  在vue3中使用vuex 4.x

vuex怎么传递数据到modules中,并获取数据 - 简书

vuex namespaced的作用以及使用方式_不屑哥的专栏-CSDN博客

提交 获取 getters、commit

const getters = {sidebar: state => state.app.sidebar,visitedViews: state => state.app.visitedViews,token: state => state.user.token,avatar: state => state.user.avatar,name: state => state.user.name,introduction: state => state.user.introduction,status: state => state.user.status,roles: state => state.user.roles,menus: state => state.user.menus,elements: state => state.user.elements,setting: state => state.user.setting,permission_routers: state => state.permission.routers,addRouters: state => state.permission.addRouters,
};
export default getters

vuex中的store分模块管理,需要在store的index.js中引入各个模块,为了解决不同模块命名冲突的问题,将不同模块的namespaced:true,之后在不同页面中引入getter、actions、mutations时,需要加上所属的模块名

1、声明分模块的store时加上namespaced:true

使用模块中的mutations、getters、actions时候,要加上模块名,例如使用commint执行mutations时

格式:模块名/模块中的mutations

xxx/setUserInfo

this.$store.commit("userInfo/setUserInfo",userInfo)

3、获取属性时同样加上模块名

格式:store.state.模块名.模块属性

$store.state.userInfo.userName
Vue3
// 导入相关apiimport {computed} from 'vue';import {useStore} from 'vuex';export default {name: 'Home',setup() {const store = useStore();let name = computed(() => store.state.user.name); // 这里注意指定user模块return {name,setToken: () => store.commit('user/SET_TOKEN', new Date().getTime() / 1000),// 这里注意指定user模块}},}第一步:
import store from "@/store";//state
store.state.count
store.state.moduleA.countthis.$store.state.count
this.$store.state.moduleA.count//获取getters里面的token
store.getters.tokenthis.$store.getters.moduleA.num//mutation 提交
store.commit('RESET_TOKEN','参数');
store.commit('user/RESET_TOKEN','参数');this.$store.commit('moduleAMutation/RESET_TOKEN');mutations: {increment (state, payload) {state.count += payload.amount}
}//action 提交
store.dispatch("user/ssologin");
store.dispatch("user/login",null);this.$store.dispatch(`${moduleName}/getContractNumber`,'参数')actions: {increment (context) {context.commit('increment')}increment ({ commit, state }, params) {commit('increment','参数')}
}

vue是做单页应用的,多个页面会有多个vue对象 刷新store会清空 ,多页面用sessionStorage传值,多页面用 buildBankManager: state => state.buildBankManager.buildBankManager, 获取Vuex 改变后的值 会被刷新清空成为初始值.所以vuex取值跳转不能在新页面打开,否则会被刷新清空成为初始值

https://segmentfault.com/a/1190000016147752

https://segmentfault.com/a/1190000015782272

vuex - 搜索结果 - 知乎

https://www.jb51.net/article/173817.htm 在vue中使用vuex,修改state的值示例

vuex中的state、getters、mutations、actions之间的关系

首先用命令安转 Vuex

npm install vuex

状态管理中 state 就相当于 vue中 data属性,getters就相当于vue中的computed属性,mutations, actions就相当于vue中的methods,只是操作方式变了而已。

更新getters里面的数据:向state提交数据的方法 mutations,处理一系列同步任务的方法

处理一个异步任务:vuex提供了一个actions来做这些异步任务

在main.js 里面引入

import store from './store/store'

首先我们在src目录下新建一个 store 目录,在store 目录下在新建一个modules目录,表示模块的意思,根据上图,我们有两种状态,显示跟隐藏

我们在modules目录下新建一个 footerStatus.js 名字随便起的,

const state = { //要设置的全局访问的state对象showFooter: true,changableNum: 0
}
// 是不是很像那个data中的数据
// 只不过这里我们把他提取出来赋值给一个 state 变量

你已经可以用this.$store.state.showFooter或this.$store.state.changebleNum在任何一个组件里面获取showfooter和changebleNum定义的值 模块(footerStatus) console.log(this.$store.state.footerStatus.changableNum)

在data属性中,我们可以在 methods 中定义各种函数,就像下面这样来操作data中数据

methods: {getValue(){return this.showFooter;}
},
computed: {showFooter(value) {this.showFooter = value;}
}

于是,我们要是想获取state里面的数据怎么办呢?这个时候,人们就想到了在getters里面定义一系列操作state的方法

const getters = {isShow(state) { //实时监听state值的变化(最新状态)return state.showFooter //方法名随意,主要是来承载变化的showFooter的值},getChangedNum() {  //方法名随意,主要是用来承载变化的changableNum的值return state.changebleNum}
}

console.log(this.$store.getters.footerStatus.isShow.length) 不能这样访问  {{ this.$store.getters.gettersCount }} 页面里的引用

state 保存了组件的数据
如果想要在组件中使用msg这个数据,最简单的
直接          模板中{{$store.state.msg}}    函数中this.$store.state.msg
想要好看,则         computed: {            msg () {              return this.$store.state.msg // 其他地方就可以直接使用msg  }         }         getter 在组件中使用时和state方法类似,要把state改成getters
想要使用reverseMsg
直接 模板中{{$store.getters.reverseMsg}}    函数中this.$store.getters.reverseMsg
想要好看,则       computed: {         reverseMsg () {            return this.$store.getters.reverseMsg        }
}

那你可能又会想,那我如果想更新getters里面的数据,怎么办呢?于是人们又想出了向state提交数据的方法 mutations,处理一系列同步任务的方法 (mutations里的方法:commit触发)

const mutations = {show(state,params) {   //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);state.showFooter = true;},hide(state,params) {  //同上state.showFooter = false;},newNum(state, sum) { //同上,这里面的参数除了state之外还传了需要增加的值sumstate.changableNum += sum;}
}

这时候你完全可以用 this.$store.commit('show') 或 this.$store.commit('hide') 以及 this.$store.commit('newNum',6) 在别的组件里面进行改变showfooter和changebleNum的值了 this.$store.commit('footerStatus/newNum',6)

那你可能又会想我想处理一个异步任务呢,没错,vuex替你想到了这些,vuex提供了一个actions来做这些异步任务 dispatch触发

const actions = {hideFooter(context) {  //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性context.commit('hide');},showFooter(context) {  //同上注释context.commit('show');},getNewNum(context,num){   //同上注释,num为要变化的形参context.commit('newNum',num)context.commit('newNum',{a:1,b:2})}
};

actions用来异步触发mutations里面的方法,actions里面自定义的函数接收一个context参数和要变化的形参,context与store实例具有相同的方法和属性,所以它里面可以执行context.commit(' ')    (actions :dispatch触发)

外部组件里进行全局执行actions里面方法的时候,你只需要用执行

this.$store.dispatch('hideFooter')

或this.$store.dispatch('showFooter')

以及this.$store.dispatch('getNewNum',6) //6要变化的实参

this.$store.dispatch('footerStatus/showFooter', 6) //6要变化的实参

最后我们需要到处模块

export default {namespaced: true, // 用于在全局引用此文里的方法时标识这一个的文件名 进行多模块处理state,getters,mutations,actions
}

同理新建一个collection.js,理解步骤同上

import {bind
} from "@/api/port";//引入接口// 数据状态
const state = {collects: [], // 初始化一个collects数组
}// 类似于computed属性
// get 获取状态
const getters = {renderCollects(state) {return state.collects}
}// 同步更新 状态
const mutations = {pushCollects(state, params) {state.collects.push(params)}
}// 异步更新 状态
const actions = {invokePushItems(context, params) {context.commit("pushCollects", params)},
async Home ({commit,state},param){ //commit 直接调用mutation里面的方法let sendData = await Home(param); commit('Home',sendData)},
}
//调用接口
handlebind({//绑定账号commit}, params) {return new Promise((resolve, reject) => {bind(params).then(response => {resolve(response);}).catch(error => {reject(error);});});},// 提交
async onSubmit({commit,state}, params) {const result = await getInfo()console.log(result)return new Promise((resolve, reject) => {axios.post(`${INTERFACE.SUBMIT_INFO}/${result.num}/products`, {...params}).then(data => {resolve(data)}).catch((err) => {window.Alert(err)  // 全局错误提示})})
}Home(context, vm){return new Promise((resolve, reject) => {axios.post('/realNameUtils/gotoStatusPage').then((res)=>{context.commit('certificationStatus',res.data.content)})})}}// 到处模块
export default {namespaced: true,state,getters,mutations,actions
}

最后我们统一在 index.js 里面到处使用 console.log(this.$store.state.footerStatus.changableNum)

import Vue from "vue"
import Vuex from "vuex"
import footerStatus from './modules/footerStatus'
import collection from './modules/collection'Vue.use(Vuex)export default new Vuex.Store({modules: { // 这里声明两个模块,后面使用就知道为啥要这样搞了collection,footerStatus}
})

接下来我们先在 main.js 导入 store/index.js   :    import store from './store/store'

接下来我们编写组件来应用上面的状态

首先在我们的views目录新建一个StatusTest.vue,比较简单,无需多言

<template><div class="state-test-wrap">我的state状态管理的学习demo</div>
</template

接下来再新建一个文件 Test.vue   mapState,mapGetters,mapActions的使用,首先 在需要用的 组件里面先导入 import {mapState,mapGetters,mapActions} from 'vuex';    this.$store.dispatch('footerStatus/showFooter')已经算是一种执行相应模块的action里的方法了

<template><div class="test-wrap"><v-state-test v-if="isShow"></v-state-test><ul v-if="allList.length"><li :key="index" v-for="(item, index) in allList">编号:{{item.id}} ----姓名:{{item.name}} ----性别:{{item.sex}}</li></ul><p><button class="hide" @click="hide">隐藏</button><button class="show" @click="show">展示</button><button class="addList" @click="invokePushItems(items)">异步提交数据</button><button class="addList2" @click="pushCollects(items)">同步提交数据</button></p></div>
</template>
<script>
import StateTest from "@views/StateTest.vue"
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
export default {name: "test",data() {return {items: {id: 0,name: "ljw",sex: "man"}}},components: {"v-state-test": StateTest,},computed: {...mapState({ // 这里的...是超引用,ES6的语法,意思是state里有多少属性值我可以在这里放多少属性值isShow: state => state.footerStatus.showFooter, // 里面定义的showFooter是指footerStatus.js里state的showFooterallList: state => state.collection.collects, // 获取 collects}),// 你也可以使用下面的方式来获取 isShow 的值// footerStatus指的是modules文件夹下的footerStatus.js模块// 第一个isShow是我自定义的只要对应template里v-if="isShow"就行,// 第二个isShow是对应的footerStatus.js里的getters里的isShow...mapGetters('footerStatus', {isShow: 'isShow',}),...mapGetters('collection', {allList: 'renderCollects'})},methods: {hide() {this.$store.dispatch("footerStatus/hideFooter")},show() {this.$store.dispatch("footerStatus/showFooter")},// 异步提交数据...mapActions('collection',["invokePushItems"]),...Vuex.mapActions({getGetTaskList: "GoUpgradetask/GetTaskList",}),// 同步提交数据...mapMutations('collection', ["pushCollects"]),}
}
</script>

访问 state、getters、mutations、actions  组件中调用Vuex的state,getters,mutations,actions,modules的数据传递、传参问题_林中明月间丶-CSDN博客

state:

前提:import {mapState,mapGetters,mapActions} from 'vuex'; //先要引入
state:
<span>获取父store中的state下的count值:{{this.$store.state.count}}</span>
<span>获取moduleA模块中的state下的count值:{{this.$store.state.moduleA.count}}</span>
<script>import {mapState} from 'vuex';export default {name: "Body",computed: {//获取父store中的state下的count值...mapState(['count']),//获取moduleA模块中的state下的count值...mapState({countA:state=>state.moduleA.countA}),}}
</script>

getters:

moduleAGetter:(state,rootState,rootGetters)=>(param,name)=>{console.log(param)console.log(name)}
<script>import {mapGetters} from 'vuex';export default {name: "Body",computed: {//1.普通情况下,分为如下两种情况:commonGetter(){//⑴无参数引用getterreturn this.$store.getters.moduleAGetter;//⑵有参数引用getter,该这么传(亦可传递对象)。或者这样子传也好:commonGetter(id,name){...}return this.$store.getters.moduleAGetter(996,'Mr.Liu');//请查看上面模块中定义的moduleAGetter方法。             },//2.mapGetters辅助函数,分为如下三种情况://⑴无参数引用getter...mapGetters(['moduleAGetter','moduleAGetter2']),//⑵无参数引用getter,更名情况下...mapGetters({changeNameGetter:'moduleAGetter'}),//⑶有参数引用getter//暂未找到mapGetter如何使用辅助函数传参情况,如有知道,欢迎大家补充},// 你也可以使用下面的方式来获取 isShow 的值// footerStatus指的是modules文件夹下的footerStatus.js模块// 第一个isShow是我自定义的只要对应template里v-if="isShow"就行,// 第二个isShow是对应的footerStatus.js里的getters里的isShow...mapGetters('footerStatus', {isShow: 'isShow',}),...mapGetters('collection', {allList: 'renderCollects'})}
</script>

mutations:

模块中的mutaion中,默认第一个传递参数是state,这个是Vuex定死的的,剩下的自定义参数部分
//个人研究发现我们只能传递一个。如果要传递多个参数,只能以对象的形式传递。如有错误或者指正,欢迎
<script>import {mapGetters,mapActions,mapMutations} from 'vuex';export default {name: "Body",methods: {//如果要传参 推荐1⑴changeMsg () {this.$store.commit('changeMsg2', {msg: '组件中的值', a: 2})}// 不传参 推荐 2⑵...mapMutations(['moduleAMutation']),// 领取名字 3⑶...mapMutations({changeNameMutation:'moduleAMutation'}),⑷paramMutation(obj){this.$store.commit('moduleAMutation',obj);},⑸...mapMutations(obj){//传参,使用辅助函数,参数目前我研究完,只能传递到上<button @click="paramMapMutation({id:996,name:'Mr.Liu'})"><button>调用的地方paramMapMutation:'moduleAMutation',})}}
2\3 触发传参
<button @click="changeMsg2({msg: '组件中的值', a: 2})">触发mutations 改变值</button>...mapMutations(['changeMsg2']),<button @click="changeNameMutation({msg: '组件中的值', a: 2})">触发mutations 改变值</button>
...mapMutations({changeNameMutation:'changeMsg2' }),
changeMsg () {this.$store.commit('changeMsg2', {msg: '组件中的值', a: 2})}

actions:

<script>import {mapGetters,mapActions,mapMutations} from 'vuex';export default {name: "Body",methods: {⑴commonAction(){this.$store.dispatch('moduleAAction')},triggerActions1 () {this.$store.dispatch("Testmodule/getUsers",this.canshu);},直接用action里面的函数⑵...mapActions(['moduleAAction']),另取名字 推荐3⑶...mapActions({changeNameAction:'moduleAAction'}),...mapActions({getUsers3: "Testmodule/getUsers"}),...Vuex.mapActions({getGetTaskList: "GoUpgradetask/GetTaskList",}),⑷paramAction(id,name){this.$store.dispatch('moduleAAction',id,name);this.$store.dispatch('moduleAAction',{a:1,b:2});},⑸...mapActions({//传参,使用辅助函数,参数目前我研究完,只能传递到上面<button @click="paramMapAction({id:996,name:'Mr.Liu'})"><button>调用的地方paramMapAction:'moduleAAction'})}}
created() {// 在这里进行分发action// this.$store.dispatch("moduleAAction", 2);this.changeNameAction({id:2,name:du})//传参this.getGetTaskList({SearchTxt: "" //搜索条件(可选填)});//传参var param = JSON.stringify({ProjectName: this.projectname ? this.projectname : "",});this.getGetTaskList(param);},
</script>

Vuex使用以及模块化\namespaced 命名空间相关推荐

  1. vuex的命名空间有哪些_vuex模块化和命名空间的实例代码

    这篇文章给大家介绍的内容是关于vuex模块化和命名空间的实例代码 ,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 因为Vuex Store是全局注册的,不利于较大的项目,引入模块分离 ...

  2. JS~~~ 前端开发一些常用技巧 模块化结构 命名空间处理 奇技淫巧!!!!!!...

    前端开发一些常用技巧               模块化结构       &&&&&     命名空间处理 奇技淫巧!!!!!!2016-09-29    17 ...

  3. vuex基础到模块化

    什么是Vuex 在Vue中,多组件的开发给我们带来了很多的方便,但同时当项目规模变大的时候,多个组件间的数据通信和状态管理就显得难以维护.而Vuex即将状态管理,可以简单理解为全局变量.Vuex采用和 ...

  4. element vue 动态单选_软件更新丨vue-element-admin 4.0.0 beta 发布,后台集成方案

    vue-element-admin 4.0.0 beta 发布了. vue-element-admin 是一个后台集成解决方案,它基于 vue 和 element.它使用了最新的前端技术栈,内置了 i ...

  5. vuex结合php,Vuex模块化(module)实例详解

    本文主要和大家介绍Vuex 模块化(module),小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助到大家. 一.为什么需要模块化 前面我们讲到的例子都在一个状态树里进行,当一个项目比较 ...

  6. vuex的mapState,mapGetters,mapActions,mapMutations与模块化

    mapState 和mapGetters 用于生成计算属性computed mapState({"计算属性名":"State数据","xxx" ...

  7. Vuex 模块化与项目实例 (2.0)

    Vuex 强调使用单一状态树,即在一个项目里只有一个 store,这个 store 集中管理了项目中所有的数据以及对数据的操作行为.但是这样带来的问题是 store 可能会非常臃肿庞大不易维护,所以就 ...

  8. Vuex的store中的Module

    Vuex的store中的Module 1.单一状态树: 什么是单一状态树呢?单一状态树可以简单得理解成整个vuex中只有一个store对象. 这是官方对单一状态树的解释: Vuex 使用单一状态树-- ...

  9. Vue状态管理vuex

    转: https://www.cnblogs.com/xiaohuochai/p/7554127.html 前面的话 由于多个状态分散的跨越在许多组件和交互间各个角落,大型应用复杂度也经常逐渐增长.为 ...

最新文章

  1. Python匿名函数:lamdba()函数
  2. 内存管理单元MMU学习
  3. androidid什么时候会变_今天是“三九”为什么老话说:三九冰上走一走,过年也能露一手!...
  4. T-SQL - 访问远程数据库并对其数据表进行操作
  5. HNOI2018酱油记
  6. Object-C 入门
  7. 3dmax天光渲染设置_【扮家家云渲染效果图】3dmax测试全局照明效果|干货教程...
  8. 服务器云平台 系统,服务器云平台 系统
  9. 本地wamp的Internal Server Error错误解决方法
  10. 对象可以在栈上分配空间吗?_Java面试题之:Java中所有的对象都分配在堆中吗?...
  11. PowerDesigner连接mysql逆向生成pdm
  12. 拓端tecdat:R语言GARCH建模常用软件包比较、拟合标准普尔SP 500指数波动率时间序列和预测可视化
  13. Leap抓取物体,在自带案例的基础上修改
  14. 【优化算法】变色龙算法(CSA)【含Matlab源码 1796期】
  15. Matable实现利用互相关函数求相位差
  16. “因遭勒索软件攻击,我被认定工作失职开除,并被老东家索赔 21.5 万元”
  17. 教育培训机构屡遭投诉?湖南中创教育给出三点建议
  18. Auto.js 9版本 OCR 文字识别
  19. 视频收集、视频征集、视频采集、征集视频、收集视频、采集视频工具/小程序
  20. linux大作业聊天室报告,Linux聊天室系统期末大作业.docx

热门文章

  1. LC正弦波振荡器【高频电子线路】【Multisim】
  2. [宋史学习] 赵光义如何篡权
  3. 【Android,Kotlin】No type arguments expected for class Call
  4. n1怎么进入线刷模式_中国移动M821(N1)官方固件刷机教程_线刷|救砖教程图解
  5. ACL 2018 ACCEPTED PAPER
  6. 字节跳动大数据岗位面经(一面、二面、三面、hr面,base南京)
  7. css实现网页背景图片位置不随滚动条改变
  8. 协议 + socket import 和 form xx import *的区别 028
  9. “传统文化传承人暨未来经济人才研修班”首期在山东省成功举办
  10. Git 常用基本操作