v-router4写法总结
写在前面:这一篇是关于我在使用vue3制作项目的时候,总结的一些关于router4路由写法的记录文章,主要用来说明vue2迁移vue3的过程中router插件的使用差异
引入
1.新建文件夹router,创建router.ts配置文件,根据个人项目习惯创建路由对象并导出
import { createRouter, createWebHashHistory } from "vue-router";
const routes:Array<any> =  [
    ...路由表
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
});
export default router;
2.main.ts引入router并使用
import router from './router';
createApp(App).use(router);
使用route对象
//vue2
console.log(this.$route.query.id);
//vue3
import { useRoute } from 'vue-router'
setup(){
    const route = useRoute();
    console.log(route.query.id)
}
使用router对象
//vue2
this.$router.push({name:'main'});
//vue3
import { useRouter } from 'vue-router'
setup(){
    const router = useRouter();
    router.push({name:'main'})
}
添加路由守卫
//main.ts设置全局路由守卫
router.beforeEach((to, from, next) => {
    store.commit('changeActive',to.meta.title)
    next();
})
//组件内设置局部路由守卫
import { useRouter,onBeforeRouteUpdate  } from "vue-router";
setup(){
    onBeforeRouteUpdate ((to,from) => {
        // 路由改变;
    })
    onBeforeRouteLeave((同.from) => {
        //路由离开
    })
}
//路由独享守卫(接下条)
路由表设置
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
-----------------------------------------
const router = new VueRouter({
  routes: [
    {
      path: '/',
      alias:["/aa","/bb"],//路由别名
      redirect:'home',    //路由重定向1
      redirect:"/home",   //路由重定向2
      props:true,         //props传参(可以在页面的props里面获取到路由传值)
      components: {       //命名视图
        default: Foo,
        a: Bar,
        b: Baz            
      },
      beforeEnter:(to,from) =>{
        console.log('我是路由独享守卫')
     }
    }
  ]
})
路由方法
<!--addRouter-->
router.addRoute({ name: 'admin', path: '/admin', component: Admin })// 添加一级路由
// 第一个参数是父路由的name名,后面是子路由的数据
router.addRoute('admin', { path: 'settings', component:AdminSettings})//添加子路由
<!--removeRouter-->
router.removeRoute('router');
End
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
 
                     
     
        
       
        
       
        
       
        
       
    
发表评论
还没有评论,快来抢沙发吧!