欢迎访问宙启技术站
智能推送

vue-router路由的示例分析

发布时间:2023-05-18 04:41:17

Vue-router是Vue.js官方路由插件,它可以让我们在Vue.js单页应用中实现页面的跳转、动态参数传递、路由嵌套等功能。下面我们来看一个Vue-router的示例分析。

我们的示例是一个简单的单页面应用,包含两个路由页面:Home和About。

1. 安装vue-router

首先安装vue-router模块,可以使用npm或者yarn

npm:

npm install vue-router --save

yarn:

yarn add vue-router

2. 配置router

在Vue.js应用中使用路由插件,需要在main.js中导入router实例,并在Vue实例中挂载。

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

Vue.use(VueRouter)

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

const router = new VueRouter({
  routes
})

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

以上代码中先安装vue-router模块,并在main.js中导入vue-router插件。接着,定义两个路由页面Home和About,使用routes数组声明路由规则。通过pathcomponent指定路由页面的路径和组件。

最后,创建一个VueRouter实例,并将声明的路由规则传入,并在Vue实例中挂载router实例。

3. 在组件中使用路由

在组件模板中,使用router-link组件来实现路由跳转,使用router-view组件来展示路由页面。

<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome to the home page</p>

    <router-link to="/about">Go to about page</router-link>

  </div>
</template>

以上代码中,通过router-link组件将当前页面导航到/about路径的路由页面。to属性指定跳转路径。

<template>
  <div>
    <h1>About Page</h1>
    <p>Welcome to the about page</p>

    <router-link to="/">Go to home page</router-link>

  </div>
</template>

以上代码中,通过router-link组件将当前页面导航到/路径的路由页面。

4. 动态路由

动态路由是指路由参数可以根据用户输入实时变化的路由。例如,我们有一个商品详情页面,每个商品有不同的商品ID,我们需要根据商品ID来显示不同的商品详情信息。这个时候就需要用到动态路由。

{
  path: '/product/:id',
  name: 'Product',
  component: Product,
  props: true
}

以上代码中,使用:来声明动态路由参数id。参数值将根据用户输入而实时变化。使用props: true将动态参数映射到组件的props属性中。

在Product组件中使用props接收路由参数:

props: {
  id: {
    type: String,
    required: true
  }
}

以上代码中,通过定义props属性接收路由参数id。参数类型通过type属性指定,是否必要通过required属性指定。

在template模板中,使用路由参数:

<template>
  <div>
    <h1>{{ id }}</h1>
    <p>{{ description }}</p>
  </div>
</template>

以上代码中,使用路由参数id来展示商品ID,使用description来展示商品描述信息。

总结

以上就是一个Vue-router的示例分析。Vue-router能够方便地实现单页应用程序的路由功能,让我们在Vue.js应用中实现页面的跳转、动态参数传递、路由嵌套等功能。通过这个示例,我们对Vue-router有了一个初步的认识和了解。