vite后台实战项目实录(二)

1、vue-router 路由
1.1 官网
https://router.vuejs.org/zh/

 1.2 安装

npm install vue-router@4

1.3 配置
router/index.js 文件
//1. 导入vue-router相关函数
import { createRouter, createWebHashHistory } from "vue-router"
// 2.路由规则
const routes = [
 {
      path:"路由地址",
      name:"路由名称",
      component:组件名称
   }
]
// 3.路由对象实例化
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
// 暴露导出
export default router
main.js 文件
import { createApp } from 'vue'
import './style.css'
// 引入element依赖文件
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 导入router配置文件
import router from "./router"
import App from './App.vue'
const app = createApp(App)
// 挂载文件
app.use(ElementPlus)
app.use(router)
// 引入windi.css
import 'virtual:windi.css'
app.mount('#app')

1.4路径别名设置

vite.config.js 文件
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import WindiCSS from 'vite-plugin-windicss'
// 1.导入node的path路径模块
import path from "path"
// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      // 配置别名
      "~": path.resolve(__dirname, "src")
   }
 },
  plugins: [vue(), WindiCSS()]
})
1.5.添加404页面
1.5.1 创建404页面组件 Page404.vue
<!-- 视图层 -->
<template>
  <div>
    <img
      src="../assets/img/page404.png"
      alt=""
      style="display: block; width: 60%; margin: 0px auto"
    />
  </div>
</template>
<!-- 逻辑层 -->
<script setup>
</script>
8.2 配置404路由
<!-- 样式层 -->
<style lang="" scoped>
</style>
1.5.2 配置404路由
//1. 导入vue-router相关函数
import { createRouter, createWebHashHistory } from "vue-router"
// 导入页面组件
import Home from "~/views/Home.vue"
import NotFound from "~/views/Page404.vue"
// 2.路由规则
const routes = [
   {
        path: "/",
        redirect: "/home"
   },
   {
        path: "/home",
        component: Home
   },
   {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound
   },
]
// 3.路由对象实例化
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
// 暴露导出
export default router

猜你喜欢

转载自blog.csdn.net/xiaowu1127/article/details/128549153