标签:return getters actions state context vue3 vuex id
<template> <div class="app"> 姓名:{{$store.state.nameVuex}} <button @click="btn">基本方法 : 修改名字</button> <br/> <button @click="btn1">传递值 : 修改名字</button> <h3>方法(映射状态) : 只适合vue2</h3> <button @click="changgeNameAction">基本方法 : 修改名字</button> <br/> <button @click="changgeName1Action('传递值')">传递值 : 修改名字</button> </div> </template> <script setup> import { useStore, mapActions } from 'vuex' const store = useStore() // 1.在setup中使用mapActions辅助函数 const actions = mapActions(["changgeNameAction", "changgeName1Action"]) const newActions = {} Object.keys(actions).forEach(key => { newActions[key] = actions[key].bind({ $store: store }) }) const { changgeNameAction, changgeName1Action } = newActions // 2.使用默认的做法 function btn() { store.dispatch("changgeNameAction") } function btn1() { store.dispatch("changgeName1Action",'任意值') } </script>
import { createStore } from 'vuex' export default createStore({ state: { nameVuex:'yjx', levelVuex:100, avtarURLVuex:'http', counterVuex:100, friends:[ {id:111,name:'why0',age:20}, {id:112,name:'why1',age:30}, {id:113,name:'why2',age:26} ] }, // 计算属性 参数1:state 参数2:getters getters: { // 基本使用 counterGetter(state){ return state.counterVuex * 2 }, usersAgesGetter(state){ return state.friends.reduce((pre,item)=>{ return pre+item.age },0) }, // 使用其他的getters : 采用参数2 message(state,getters){ return `名字:${ state.nameVuex } , 等级 :${ state.levelVuex} , 朋友年龄总和 ${getters.usersAgesGetter}` }, // 获取某id的朋友 firendId(state){ return function(id){ return state.friends.find(item=>item.id === id) } } }, // mutations : 想修改state的值必须通过mutations来修改 // mutations 参数1:state的 参数2.传递过来的数据 mutations: { changgeName(state){ state.nameVuex = '吴宇腾' }, changgeName1(state,payload){ state.nameVuex = payload } }, // 参数1:context 参数2:传递过来的 //可以通过context.state来获取state //可以通过context.getters来获取getters, //可以通过context.commit('') 来提交mutations //发送请求,都是在actions里面的 actions: { changgeNameAction(context){ context.commit('changgeName') }, changgeName1Action(context,payload){ context.commit('changgeName1',payload) } }, modules: { } })
标签:return,getters,actions,state,context,vue3,vuex,id 来源: https://www.cnblogs.com/qd-lbxx/p/16638561.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。