vue router

引入vue-router

 可以通过以下方式引入:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

// 在这里定义你的路由和组件
const routes = [
  // ...
];

const router = new VueRouter({
  routes,
});

// 将 router 添加到 Vue 实例中
new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');

vue-router 特色标签及作用

  1. <router-link>:用于生成页面中的链接,使用户可以点击导航到不同的页面。

  2. <router-view>:用于显示当前路由匹配到的组件。

使用vue-router设计路由

在上述的代码中,routes 数组用于定义路由。每个路由对象包含 path(路径)和 component(对应的组件)等属性。

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  // ...其他路由
];

历史记录在vue-router中的使用

Vue Router 使用 HTML5 历史模式和 hash 模式来管理路由。在创建 VueRouter 实例时,可以通过 mode 属性来指定使用的模式:

const router = new VueRouter({
  mode: 'history', // 或 'hash'
  routes,
});

路由传参

可以在路由路径中使用动态片段来传递参数:

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

在组件中,可以通过 $route.params.id 来获取参数值。

实现嵌套路由

嵌套路由是通过在父路由的组件中使用 <router-view> 来实现的。在路由配置中,可以嵌套定义子路由:

const routes = [
  {
    path: '/parent',
    component: Parent,
    children: [
      { path: 'child', component: Child },
    ],
  },
];

命名视图

通过 name 属性为路由视图命名,以支持多个视图的同时显示。

const routes = [
  {
    path: '/',
    components: {
      default: Home,
      sidebar: Sidebar,
      footer: Footer,
    },
  },
];

重定向

使用 redirect 属性来实现路由重定向:

const routes = [
  { path: '/a', redirect: '/b' },
];

导航守卫分类

导航守卫用于在路由发生变化时执行一些操作。主要分为全局守卫、路由独享守卫、组件内守卫。

  • 全局守卫beforeEachafterEachbeforeResolve
  • 路由独享守卫:在路由配置中使用 beforeEnter
  • 组件内守卫beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave

路由元信息和路由过渡动效

路由元信息是一个对象,可以在路由配置中添加,用于存储一些额外的信息。

const routes = [
  { path: '/example', component: Example, meta: { requiresAuth: true } },
];

路由过渡动效可以通过在组件中使用 <transition> 来实现,或者通过 router-view 上添加 name 属性。

动态路由

通过使用动态路径参数,可以实现动态路由:

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

在组件中,通过 $route.params.id 获取动态参数的值。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值