(十六)Vue3.x中使用vue-router的新特性

本章我們將聊到Vue-Router在vue3.x中的使用方式及特性。

1、描述:區(qū)別于vue2,在vue3中,vue-router將使用新的方法來創(chuàng)建路由,其中重要的是:createRouter, createWebHashHistory, createWebHistory這三個方法。
2、創(chuàng)建:

// router.js
import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
const routes = [...];
const router = createRouter({
  // 區(qū)別于vue2的mode,vue3中將使用history屬性來決定采用哪種路由模式
  history: createWebHashHistory(), // 默認為Hash模式,可設置createWebHistory模式
  // 區(qū)別于vue2的base,vue3中的基礎路由路徑將作為createWebHashHistory或者createWebHistory的唯一參數配置到路由中。
  routes
});
export default router;

// main.js
import router from './routes';
const app = createApp(App);
// 注冊路由
app.use(router);

3、擴展:在組件中使用路由,查看路由。

// index.vue
// vue-router庫當中暴露了useRouter和useRoute兩個方法供組件使用,還暴露有其他方法。
import { useRouter, useRoute } from 'vue-router';
import { onMounted, getCurrentInstance } from 'vue';

export default {
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const route = useRoute();
    onMounted(() => {
      console.log(proxy.$router === router) // true
      console.log(route) // {path, params, query...}
    });
  }
};

下一章:(十七)Vue3.x使用provide/inject來代替vuex的實現方式
上一章:(十五)Vue3.x中我們將采用mitt實現全局事件總

ps:未來的,我期待著;過去的,我釋懷著;可都不及我珍惜的,眼前的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容