学习笔记:vue-router(4.x) 与 vue-router(3.x)的区别

5,307 阅读1分钟

开头

  • 年初建立flag,今年要写99文章,纯粹就是个人的学习笔记!
  • 由于刚开始写文章,有什么问题可以及时指出,会在第一时间改正!
创建方式
  • createRouter
  • 用来创建router对象
  • 4.x用法
import { createRouter } from "vue-router"
const router = createRouter({
    // opyions
    .....
})
  • 3.x用法
import VueRouter from "vue-router"'
const router = new VueRouter({
    // options
    ......
})

路由模式

  • createWebHashHistory (hash)
  • createWebHashHistory (history)
  • 4.x用法
import { 
    createRouter,
    createWebHashHistory,
    createWebHashHistory
} from 'vue-router'
const router = createRouter({
    history:createWebHashHistory() / createWebHashHistory()
})
  • 3.x用法
 const router = new VueRouter({
    mode: 'hash' / 'history'
 })

重定向

  • 写法有所改变
  • 4.x的写法
{
    path: '/:pathMatch(.*)*', // 需要使用正则去匹配
    redirect: Home,
}
  • 3.x的写法
{
    path: '*',
    redirect: Home
}

挂载方式

  • 因为vue3的composition api,vue-router的挂载方式以插件来挂载
  • 4.x的用法
    import { createApp } from 'vue'
    import router from './router.js'
    import App from './App.vue'
    createApp(App).use(router).mount('#app');
  • 3.x的用法,以属性的方式进行挂载
 import router from './router.js'
   new Vue({
      router
   })

组件中的使用

  • 因为setup中不能访 this,所以提供两个api来获取 routerrouteuseRouter()useRoute()
  • 4.x的用法
   import { useRouter,useRoute } from "vue-router"
   export default({
      setup(){
        const router = useRouter();
        const route = useRoute();
        const linkToHome = () => {
            router.push({
                path:'/'
            })
        }
        return{
            linkToHome
        }
      }
   })
  • 3.x的用法
    export default({
       methods:{
         linkToHome(){
           this.$router.push({
                   path:'/'
               })
         }
       }
    })

导航守卫

  • 由于vue3 composition api的原因,beforeRouteUpdate 和 beforeRouteLeave被替换为 onBeforeRouteUpdate 和 onBeforeRouteLeave