当前位置: 首页 > Web前端 > vue.js

vuex-router-sync使用方法

时间:2023-04-01 01:40:14 vue.js

简单来说,vuex-router-sync插件就是将vue-router的状态同步到vuex1.安装npm下载地址:https://www.npmjs.com/package...>npmivuex-router-sync--save2.使用import{sync}from'vuex-router-sync'importstorefrom'./vuex/store'importrouterfrom'./router'sync(store,router,{moduleName:'RouteModule'})constapp=newVue({router,store,}).$mount('#app');printstore.state查看当前路由状态3.使用场景如果你想在一个组件中显示一条消息,想在几乎所有页面上显示“Haveaniceday,Jack”,除了首页,因为首页应该显示“欢迎回来,杰克”。使用vuex-router-sync,你可以轻松实现constTop={template:'

{{message}}
',computed:{message(){returnthis.$store.getters.getMessage;}},};constBar={template:'
{{message}}
',computed:{message(){returnthis.$store.getters.getMessage;}}};constroutes=[{path:'/top',component:Top,name:'top'},{path:'/bar',component:Bar,name:'bar'},];constrouter=newVueRouter({routes});conststore=newVuex.Store({state:{用户名:'Jack',phrases:['Welcomeback','Haveaniceday'],},getters:{getMessage(state){returnstate.route.name==='top'?`${state.phrases[0]},${state.username}`:`${state.phrases[1]},${state.username}`;},},});//使用`vuex-router-sync`sync(store,router)同步store和router;constapp=newVue({router,store,}).$mount('#app');否则,你可能需要在vue-router的hook函数中监听,或者watch中的$route,然后修改store值来实现4.原理在70多行的vuex-router-sync源码中,有是以下代码段transition.to,transition.from)}}})首先在我们的store中注册了一个模块,名称默认为route:模块中提供了一个突变处理方法叫做ROUTE_CHANGED,然后router对象中的currentRoute为保存在state中,这也是为什么我们可以通过this.$store.state.route获取currentRoute的原因。然后就是监听store中route对象的变化。当路由发生变化,当前路由名称不等于需要跳转到路由时,直接使用路由器的push方法跳转到页面:varstoreUnwatch=store.watch(function(state){returnstate[moduleName];},function(route){varfullPath=route.fullPath;if(fullPath===currentPath){return}if(currentPath!=null){isTimeTraveling=truerouter.push(route)}currentPath=fullPath},{sync:true})store的watch方法和vue的watch是同一个概念,就是检测某个属性的变化,然后回调。最后通过路由器的全局post-hook函数监听当前路由对象,修改store中的当前状态(当前路由对象)://syncstoreonrouternavigationvarafterEachUnHook=router.afterEach(function(to,from){if(isTimeTraveling){isTimeTraveling=falsereturn}currentPath=to.fullPathstore.commit(moduleName+'/ROUTE_CHANGED',{to:to,from:from})})欢迎关注:https://www.fenxianglu。cn/参考链接:https://segmentfault.com/a/11...https://blog.csdn.net/vv_bug/...