«

Vue3安装配置路由(VueRouter)信息

时间:2023-7-28 00:21     作者:六思逸     分类: Vue


第一步: 安装路由

npm install vue-router@4

yarn add vue-router@4

第二步: 创建router目录及index.js文件

2.1 在index.js中引入包文件

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

2.2 引入组件,可以使用懒加载

import Home from '../views/Home.vue';//引入模式

2.3 配置路由数组

const routes = [
    { path: '/', component: Home },
    { path: '/info', component: () => import('../views/Info.vue') },
];

2.4 创建路由对象

const router = createRouter({
    // createWebHashHistory()--hash    |  createWebHistory()--history
    history: createWebHashHistory(),    // history还是hash  
    routes,  // 路由数组
});

2.5 将router暴露出去

export default router

第三步: 在main.js中引入使用路由

import router from 'router的路径'
const app = createApp(App) // 创建Vue应用程序实例,并传入根组件App
app.use(router)
app.mount('#app') // 将应用程序挂载到页面上的#app元素

第四步: 在APP.vue中写出口

<router-view />

完整示例

router/index.js

// 配置路由文件
import { createRouter, createWebHashHistory } from 'vue-router';
import Home from '../views/Home.vue';
// 配置路由数组
const routes = [
    { path: '/', component: Home },
    { path: '/info', component: () => import('../views/Info.vue') },
];
// 创建路由对象
const router = createRouter({
    history: createWebHashHistory(),
    routes,
});
// 暴露对象
export default router

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
const app = createApp(App) // 创建Vue应用程序实例,并传入根组件App
app.use(router)
app.mount('#app') // 将应用程序挂载到页面上的#app元素

APP.vue

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

标签: Vue Router Vue3 Vue3安装配置路由

版权所有:六思逸
文章标题:Vue3安装配置路由(VueRouter)信息
除非注明,文章均为 六思逸 原创,转载请注明作者和出处 六思逸

扫描二维码,在手机上阅读

推荐阅读: