Vue3路由机制router

目录

1. 路由简介

2. 路由运用示例

3. 路由重定向 

4. 编程式路由

5. 路由传参(useRoute)

6. 路由守卫


1. 路由简介

1 什么是路由?

  • 定义:路由就是根据不同的 URL 地址展示不同的内容或页面。

  • 通俗理解:路由就像是一个地图,我们要去不同的地方,需要通过不同的路线进行导航。

2 路由的作用

  • 单页应用程序(SPA)中,路由可以实现不同视图之间的无刷新切换,提升用户体验;

  • 路由还可以实现页面的认证和权限控制,保护用户的隐私和安全;

  • 路由还可以利用浏览器的前进与后退,帮助用户更好地回到之前访问过的页面

2. 路由运用示例

下面以 Vue.js 和 Vue Router 为例,展示基本的路由配置和使用方法。

 1. 安装 Vue Router

首先,确保你已经安装了 Vue CLI,然后在你的项目中安装 Vue Router: 

npm install vue-router

2. 基本路由配置

 创建一个简单的 Vue 应用,并配置路由:

// src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';

import Home from '../views/Home.vue';
import About from '../views/About.vue';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: About
    }
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});

export default router;

在主应用文件中引入并使用路由:

// src/main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;

new Vue({
    router,
    render: h => h(App)
}).$mount('#app');

3. 创建视图组件

// src/views/Home.vue
<template>
  <div>
    <h1>Home Page</h1>
  </div>
</template>

<script>
export default {
  name: 'Home'
};
</script>

// src/views/About.vue
<template>
  <div>
    <h1>About Page</h1>
  </div>
</template>

<script>
export default {
  name: 'About'
};
</script>

4. 启动测试

npm run dev

3. 路由重定向 

有时你可能需要将用户从一个路由重定向到另一个路由。Vue Router 提供了一个简单的方法来处理重定向。

const routes = [
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: About
    }
];

在上面的例子中,当用户访问根路径 / 时,他们会被重定向到 /home

4. 编程式路由

编程式路由允许你在代码中动态导航到不同的路由。Vue Router 提供了 $router 对象上的 pushreplace 方法来实现这一点。

methods: {
    goToAbout() {
        this.$router.push({ name: 'About' });
    }
}

使用 push 会添加一个新的历史记录,而 replace 则会替换当前的历史记录。

methods: {
    replaceWithAbout() {
        this.$router.replace({ name: 'About' });
    }
}

5. 路由传参(useRoute)

有时,页面之间需要传递参数,例如在文章详情页中根据文章ID来加载特定的内容。路由库通常提供了传递参数的机制,如在Vue Router中可以使用useRoute钩子来获取当前路由的参数信息。

当你需要在路由之间传递参数时,可以使用动态路由匹配和编程式导航。

动态路由匹配

const routes = [
    {
        path: '/user/:id',
        name: 'User',
        component: User
    }
];

 在组件中,你可以通过 this.$route.params 获取路由参数:

// src/views/User.vue
<template>
  <div>
    <h1>User ID: {{ userId }}</h1>
  </div>
</template>

<script>
export default {
  computed: {
    userId() {
      return this.$route.params.id;
    }
  }
};
</script>

编程式传参

使用编程式导航传递参数:

methods: {
    goToUser(userId) {
        this.$router.push({ name: 'User', params: { id: userId } });
    }
}

6. 路由守卫

路由守卫允许开发者在路由导航前后执行特定的代码逻辑。常见的用例包括身份验证(检查用户是否登录)、权限控制(确保用户有权访问特定页面)、页面切换前的数据加载等。这些守卫可以确保应用的安全性和用户体验。

在 Vue 3 中,路由守卫是用于在路由切换期间进行一些特定任务的回调函数。路由守卫可以用于许多任务,例如验证用户是否已登录、在路由切换前提供确认提示、请求数据等。Vue 3 为路由守卫提供了全面的支持,并提供了以下几种类型的路由守卫:

全局守卫 

全局守卫适用于所有路由,通常用于权限验证:

router.beforeEach((to, from, next) => {
    if (to.name !== 'Login' && !isAuthenticated()) next({ name: 'Login' });
    else next();
});

路由独享守卫 

路由独享守卫仅应用于特定路由:

const routes = [
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        beforeEnter: (to, from, next) => {
            if (!isAuthenticated()) next({ name: 'Login' });
            else next();
        }
    }
];

组件内守卫 

组件内守卫在组件即将加载时触发:

export default {
    beforeRouteEnter(to, from, next) {
        // 在路由进入之前
        next(vm => {
            // 组件实例已经创建
        });
    },
    beforeRouteUpdate(to, from, next) {
        // 在路由更新时
        next();
    },
    beforeRouteLeave(to, from, next) {
        // 在路由离开之前
        next();
    }
};

  • 35
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值