前言
Vue.js 是一款流行的前端开发框架,它的核心是一个响应式的数据绑定系统和一个组合式的视图组件系统。Vue.js 还提供了一些插件,其中 vue-router 是用于前端路由管理的插件,它使得我们可以实现 SPA (Single Page Application) 单页应用开发。本文将详细介绍在 Vue.js 中如何使用 vue-router 实现页面跳转和参数传递。
安装与基本使用
在使用 vue-router 前,我们需要先安装它。可以使用 npm 或者 yarn 进行安装:
npm install vue-router 或者 yarn add vue-router
在 Vue.js 中使用 vue-router 也很简单,在 Vue.js 应用程序的入口文件(通常为 main.js)中引入 vue-router 并创建一个 router 实例:
-- -------------------- ---- ------- ------ --- ---- ----- ------ --------- ---- ------------ ------ --- ---- ----------- ------------------ ----- ------ - - -- ---- - ----- ---- ---------- ---- -- - ----- --------- ---------- ----- -- - ----- ----------- ---------- ------- - - ----- ------ - --- ----------- ------ -- ------- ------- ------ -- --- ----- ------- - -- ------- ------ -----------------展开代码
上面的代码片段中定义了 3 个路由,分别对应 path 为 /、/about 和 /contact。接下来,我们在 App.vue 文件中加入 <router-view> 标签以显示组件:
<template> <div> <router-view></router-view> </div> </template>
这样,我们就完成了 vue-router 的基本使用。
页面跳转
在 vue-router 中实现页面跳转只需要用到 <router-link> 标签。该标签会被编译成一个 <a> 标签,具有 href 属性,和一个点击事件,该事件会调用 VueRouter.push() 方法实现跳转。
<template> <div> <h1>Home Page</h1> <router-link to="/about">Go to About Page</router-link> </div> </template>
在上面的代码片段中,我们使用了 <router-link> 标签,to 属性为目标路由路径。
我们还可以给 <router-link> 标签添加样式,代码如下:
<router-link to="/about" class="custom-link">Go to About Page</router-link>
.custom-link { color: blue; text-decoration: underline; }
参数传递
在传递参数之前,我们需要为每个路由定义一个名称,例如:
const routes = [ { path: '/', component: Home, name: 'home' }, { path: '/about/:id', component: About, name: 'about' }, { path: '/contact', component: Contact, name: 'contact' } ]
在上述的路由配置中,我们为 /about 路由添加了一个参数 id。接下来,我们来看一下如何使用路由参数。
获取路由参数
在路由组件内部,可以使用 $route 对象来获取路由参数。例如,在 About 组件中打印出传递进来的 id:
export default { methods: { logId() { console.log(this.$route.params.id) } } }
如果有多个参数,可以通过 this.$route.params.xxx 获取。
传递路由参数
在 <router-link> 标签中传递参数可以使用属性绑定方式,例如:
<router-link :to="{ name: 'about', params: { id: 123 } }" class="custom-link" > Go to About Page </router-link>
在上述的代码片段中,我们使用 to 属性,传入一个对象,该对象中的 name 属性指定目标路由的名称,params 属性指定要传递的参数。在 About 组件中打印出参数:
-- -------------------- ---- ------- ------ ------- - -------- - ------- - ---------------------------------- -- ------ - -- --------- - ------------ - -展开代码
结语
到此,我们已经了解了在 Vue.js 中使用 vue-router 实现页面跳转和参数传递的方法。vue-router 提供的动态路由和嵌套路由等功能这里未作详细讲解,希望大家可以进一步学习和理解。
完整示例代码可前往Github获取。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67bb1c10306f20b3a6a6efb6