当前位置:主页 > 网页前端 > vue >

Vue3使用路由VueRouter4的简单示例

时间:2021-10-09 08:51:49 | 栏目:vue | 点击:

路由

vue-router4保持了大部分API不变,我们只关注变化部分即可。

安装

yarn add vue-router@4

引入

cdn

<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/4.0.6/vue-router.cjs.js"></script>

使用

router.js

import { createRouter, createWebHistory } from "vue-router";

import Home from "./views/Home.vue";

const routes = [
  { path: "/", component: Home },
  { path: "/about", component: () => import("./views/About.vue") }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

const app = createApp(App);
app.use(router);
app.mount("#app");

App.vue

<template>
  <h1>Hello App!</h1>
  <p>
    <router-link to="/">Go to Home</router-link>
    <router-link to="/about">Go to About</router-link>
  </p>
  <router-view></router-view>
</template>

<script>
export default {};
</script>

一个小提示

如果你的 App.vue 模板只有 <router-view></router-view> 时, 可以吧 <router-view> 直接放入 index.html 中。

例如:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" rel="external nofollow"  />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app">
      <router-view></router-view>
    </div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

之后 main.js 内移除 App.vue

main.js

import { createApp } from "vue";
// import App from "./App.vue";
import router from "./router";

// const app = createApp(App);
const app = createApp({});
app.use(router);
app.mount("#app");

完成!😀方便又好用

总结

您可能感兴趣的文章:

相关文章