Vue Router 4 快速入门-安装配置(js/ts)

1,116 阅读1分钟

js 与 ts 引入配置 Vue-Router4

js:

安装依赖

npm install vue-router@4
或
yarn add vue-router@4

配置 router

1.在 src 目录下创建 router 文件夹,创建 index.js

2.内容如下:

//全局配置Router
import { createRouter, createWebHashHistory } from 'vue-router'
let routes = [
    { path: '/', component: () => import('../components/xxx.vue') },
]
const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 将router/index.js暴露出去
export default router

3.在 main.js 里配置

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

// 全局配置引入Router,Router的位置在router/index.js
import router from './router'

createApp(App).use(router).mount('#app') //注意这里的挂载

4.在 app.vue 中使用<router-view></router-view>

5.测试路由跳转

<script setup>
import router from "../router/index";
const go = () => {
  router.push("/xxx");
};
</script>

ts

安装依赖

npm install vue-router@4
或
yarn add vue-router@4

配置 router

1.在 src 目录下创建 router 文件夹,创建 index.ts

2.内容如下:

import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'
// 路由懒加载
const HelloWorld = () => import('../components/HelloWorld.vue')


// 配置router对象
const router = createRouter({
    // 路由模式
    history: createWebHistory(),  //使用History模式,需要后端配合配置
    // history: createWebHashHistory(),  //hash模式
    // 动态路由/路由懒加载
    routes: [
        {
            path: "/HelloWorld",
            component: HelloWorld
        }
    ],
})

// 路由导航守卫
// router.beforeEach((to, from, next) => {
//     if (to.path === '/') { return next() }
//     let tokenStr = window.localStorage.getItem('token')
//     if (!tokenStr) return next('/')
//     next()
// });

export default router

3.在 main.js 里配置

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

// 全局配置 Router
import router from './router' //引入 router
createApp(App).use(router).mount('#app') //挂载使用 router

4.在 app.vue 中使用<router-view></router-view>

5.测试路由跳转

<script setup>
import router from "../router/index";
const go = () => {
  router.push("/xxx");
};
</script>