vue3+ts: install routing (router)

1. Install routing

       1. Install vue-router

        Vue3 needs to install version 4.0 or above

        It is best to install a version below 4.0 for vue2

        Install command:

npm install vue-router@next --save // 安装最新版本router

// 如需按版本安装,需将命令行中 next 改成相应的版本。如下:
// npm install [email protected] --save

After the installation is complete, check whether vue-router is successfully installed         in package.json

 

Second, configure the router file

Create a new router folder under the src directory, and create a new index.ts file in the router folder. The code is as follows:

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

// 1. 配置路由
const routes: Array<RouteRecordRaw> = [
  {
    path: "/", // 默认路由 home页面
    component: () => import("../views/home/index.vue"),
  },

];
// 2.返回一个 router 实列,为函数,配置 history 模式
const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 3.导出路由   去 main.ts 注册 router.ts
export default router

3. Refer to index.ts under router in main.ts

The code in main.ts is as follows:

// import { createApp } from 'vue' // 安装unplugin-auto-import 可注释
import './style.css'
import App from './App.vue'
import { createPinia } from 'pinia' // 引入pinia
import router from "./router/index" // 引入router

const app = createApp(App)
app.use(createPinia())
    .use(router)
    .mount('#app')

 4. Add routing component router-view to app.vue

<template>
  <router-view></router-view>
</template>

 At this point: the default redirection of the route is fine. After the project starts, it will jump to the home page configured in the second step.

 Sample code:

 Example page:

 

Guess you like

Origin blog.csdn.net/weixin_45440521/article/details/129318826