项目源码-Vue3项目02-路由配置

Last Updated on 2025年1月4日 by hangzi

路由配置

1、安装依赖

pnpm add vue-router

2、新建视图页面

视图页面

index.vue内容, 内容文字自己随便写:

<template>
  <div>
    <h1>首页页面</h1>
  </div>
</template>

3、新建路由

新建路由

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

const routes = [
    {
        path: '/',
        name: 'index',
        component: () => import('../views/index.vue'),
        meta: {
            title: '首页'
        }
    },
    {
        path: '/about',
        name: 'about-index',
        component: () => import('../views/about/index.vue'),
        meta: {
            title: '关于'
        }
    },
    {
        path: '/content',
        name: 'content-index',
        component: () => import('../views/content/index.vue'),
        meta: {
            title: '内容'
        }
    },
]

let router = createRouter({
    history: createWebHashHistory(),
    routes,
});

// 全局注册 router
export function setupRouter(app) {
    app.use(router);
}

export default router;

4、配置插件

配置插件

5、配置路由插件

配置路由插件

import {setupRouter} from "../router/index";

export default {
    install(app) {
        setupRouter(app)
    }
}

6、使用插件

  • main.js中引入插件

引入插件

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

//插件
import setupPlugins from './plugins'

createApp(App)
    .use(setupPlugins)
    .mount('#app')
  • App.vue中引入路由

引入路由

完整App.vue代码

<template>

  <!-- 路由列表 -->
  <ul class="list-container">
    <li v-for="route in routesList" :key="route.path">
      <router-link :to="route.path">{{ route.meta.title }}</router-link>
    </li>
  </ul>

  <!-- 渲染路由组件 -->
  <router-view/>
</template>

<script setup>
import {useRouter} from 'vue-router';
import {ref} from "vue";

const routesList = ref([])

const router = useRouter();

routesList.value = router.getRoutes();
</script>

<style >

.list-container {
  display: flex;
  list-style-type: none;
  padding: 0;
  margin: 0;
  font-size: 25px;
}

li {
  margin-right: 20px;
}

li a{
  color: #000;
  text-decoration: underline;
}

li .router-link-active {
  color: #409eff;
  font-size: 25px;
  text-decoration: inherit;
}
</style>

项目Demo源码:https://github.com/hangzhi7/Vue3-Demo


关注微信公众号『编程与读书

第一时间了解最新网络动态
关注博主不迷路~