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

vuex-router-sync实例

时间:2023-03-31 20:32:00 vue.js

1。安装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”,因为首页页面应该显示“Welcomeback,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:{username:'Jack',phrases:['Welcomeback','H祝你有美好的一天'],},getters:{getMessage(state){returnstate.route.name==='top'?`${state.phrases[0]},${state.username}`:`${state.phrases[1]},${state.username}`;},},});//使用`vuex-router-sync`同步store和routersync(store,router);constapp=newVue({router,store,}).$mount('#app');否则可能需要在vue-router的hook函数中监听,或者watch中的$route,然后修改store值实现4,原理在vuex-router-sync的70多行源码中,有以下代码片段.to,transition.from)}}})首先在我们的store中注册一个模块,默认名称为route:模块中提供了一个名为ROUTE_CHANGED的模块的变异处理方法,然后将currentRoute保存在router中状态中的对象,这就是为什么我们可以通过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})})————————————————版权声明:本文为CSDN博主“天空还在下雪”的原创文章,遵循CC4.0BY-SA版权协议,转载请附上原文出处链接及本声明。