首页 > 编程知识 正文

vue,vue3setup实际应用

时间:2023-05-05 07:12:34 阅读:28440 作者:4434

在vue3.0中使用mapState、mapGetters和mapActions 1、新useMapper.js2、新useState.js3、新useGetters.js4、新useActions.js5和页面

在vue2.0中使用映射状态和映射操作的方法

//mapstatecomputed : (map state )/.} ) methods: )…mapactions(['FNA ',' fnB'] )

在vue3.0中获取状态和使用操作

导入{ computed } from ' vue ' import { usestore } from ' vuex ' setup () {const store=useStore ); const stateA=computed ()=store.state.stateA ); const stateB=computed ()=store.state.stateB ); const methoda=store.dispatch (methoda )、{name: )结实酸奶}; }那么,如何在vue3上使用mapState等api呢?

答案是封装mapState、mapGetters和mapActions方法。

1、use mapper.js import { usestore } from ' vuex ' import { computed } from ' vue ' exportfunctionusestatemapper (映射器,mapper ) 常数storestate={ }; this绑定,因为在object.keys(storestatefns ).foreach ) fnkey={/vuex源代码的mapState和mapGetters方法中使用了this.$store=computed [ fn ] } returnstorestate } exportfunctionuseactionmapper { mapper,map fn } { conststore=} conststoreactionsfns const storeAction={}; object.keys(storeactionsfns ).foreach ) fn key={ store action [ fn key ]=storeactionsfns [ fn key ].bind ) $ store 3330 createnamespacedhelpers } from ' vuex ' import { usestatemapper } from './use mapper ' import { check type } from './index mapper state属性集合['name ',' age ' ] * @ returns */exportfunction usestate (modulename, 使用mapper //模块化,可以使用vuex提供的createNamespacedHelpers方法将相应模块的mapState方法if (check type (modulename (==' [ ' modulename.length0) ) { mapperfnfn=createnamespacedhelpers (modulename ).map state } returnusestatemapper } mapper 新建use getters createnamespacedhelpers } from ' vuex ' import { usestatemapper } from './use mapper ' import { check type } from mapper getters属性集合['name ',' age ' ] * @ returns */exportfunctionusegetters (modulename, mame //模块化使用vuex提供的createNamespacedHelpers方法,将相应模块的mapGetters方法if (check type (modulename (==' [ ' modulename.length0) ) { mapperfnfn=createnamespacedhelpers (modulename ).map getters } returnusestatemappper ) 映射器fn ) 4、新建useactionnal import { useactionmapper } from './use mapper ' import { check type } from './index '/* * * 导出函数操作(modulename,mapper ) { let mapper fn=map操作; //模块化使相应模块的mapActions方法if(checktype(modulename )===' [对象类型],使用vuex提供的createNamespacedHelpers方法' modulename.length0) ) { mapper fn=createnamespacedhelpers (modulename ).map actions } returnuseaction mapper } MP mapperFn () 5,页面上为template div class='home' span姓名({{name}}年龄) {{age}}性别) { sex }/span button @ click=' ' src import { use state } from ' @/utils/use state ' import { use actions } from ' @/utils/use action ' Expo on } setup () ccod ' sex'] ) conststoreactions=useactions ) ) home [ ' set name ' ] (const changename=()={ storeAction.setName ) )李四/脚本

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。