事关我使用router4的一些记录

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

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享