vue3整合vue-router
vue3整合vue-router
安装依赖
npm install vue-router@4在src目录下新建router/index.ts,写入一些基本路由。路由通常分为无需权限路由(比如登录)和需要权限的路由(比如某个数据页面)
index.ts内容
import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
export const publicRouters: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/home.vue'),
        meta: { title: '首页', icon: 'shouye', affix: true, sort: '99.99' },
      },
    ],
    meta: {
      sort: '99',
    },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue'),
    meta: {
      hidden: '1',
    },
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes: publicRouters,
})
export default router
vue-router指定路由模式从字符串变为了使用方法,history是createWebHistory(地址栏不带#的意思),hash是createWebHashHistory(地址栏带#的意思)。如果发现ts会报找不到vue文件相关类型声明的错误,我们可以在根目录创建一个env.d.ts,在里面写入以下内容
/// <reference types="vite/client" />
declare module '*.vue' {
  //引入vue模块中ts的方法
  import type { DefineComponent } from 'vue'
  // 定义vue組件以及类型注解
  const component: DefineComponent<{}, {}, any>
  export default component
}
然后在tsconfig.ts或者tsconfig.json中include添加
"env.d.ts"简单的定义一个主页面和登录页
主页面home.vue
<template>  
    <div class="welcome-page">  
      <h1>Welcome to My App!</h1>  
      <p>This is the welcome page.</p>  
      <!-- 添加其他元素和样式 -->  
    </div>  
</template>
<script>  
export default {  
data() {  
    return {  
    // 添加你的数据属性  
    };  
},  
methods: {  
    // 添加你的方法  
}  
};  
</script>登录页面loging.vue
<template>  
    <div class="welcome-page">  
      <h1>Welcome to My App!</h1>  
      <p>This is the welcome page.</p>  
      <!-- 添加其他元素和样式 -->  
    </div>  
</template>
<script>  
export default {  
data() {  
    return {  
    // 添加你的数据属性  
    };  
},  
methods: {  
    // 添加你的方法  
}  
};  
</script>在main.ts中进行引入路由
import router from './router'
createApp(App).use(router).mount('#app')在main.vue中写入路由<router-view></router-view>
<template>
  <router-view></router-view>
</template>至此就可以访问不同页面了
