简介
nanohref 是一个轻量级的 JavaScript 库,用于处理前端页面中的路由和页面跳转。它可以让你在不刷新整个页面的情况下动态地修改 URL 和内容,实现单页应用程序(SPA)的效果。
安装
在使用 nanohref 之前,需要先安装它。你可以通过 npm 来进行安装:
npm install nanohref
如果你使用 yarn,也可以通过以下命令来进行安装:
yarn add nanohref
使用
使用 nanohref 很简单,在你的 HTML 文件中引入它即可:
<script src="./node_modules/nanohref/nanohref.js"></script>
或者,如果你使用模块化开发,可以将其导入到你的脚本文件中:
import nanohref from 'nanohref'
路由配置
在使用 nanohref 的时候,你需要先配置好路由信息。路由信息是一个对象,其中键名为路径,值为回调函数。当用户访问某个路径时,回调函数会被触发。例如:
const routes = { '/': () => { console.log('访问了首页') }, '/about': () => { console.log('访问了关于页面') } }
初始化
配置好路由信息后,需要进行初始化,这样 nanohref 才能开始监听 URL 的变化:
nanohref(routes)
跳转页面
使用 nanohref 提供的 nanohref()
函数可以进行页面跳转。此函数接受一个字符串参数,表示要跳转的路径。例如,以下代码表示跳转到路径为 /about
的页面:
nanohref('/about')
获取参数
在路由回调函数中,可以通过 location.search
和 location.hash
来获取 URL 中的查询参数和哈希值。例如,对于以下 URL:http://example.com/?name=john#top
,可以通过以下代码来获取查询参数和哈希值:
const name = new URLSearchParams(location.search).get('name') // 'john' const hash = location.hash // '#top'
示例代码
以下是一个完整的示例代码,实现了一个简单的 SPA,包含两个页面:首页和关于页面。
-- -------------------- ---- ------- ---- ---------- --- --------- ----- ------ ------ ----- ---------------- --------- ----------- ------- ------ ----- ---- ------ -------------------- ------ ------------------------- ----- ------ ---- ------------------- ------- --------------------------------------------------- ------- -------------------------- ------- -------
-- -------------------- ---- ------- -- -------- ------ -------- ---- ---------- ----- ------ - - ---- -- -- - -------------------------------------------- - ----------------- -- --------- -- -- - -------------------------------------------- - ---------------------------------- - - ----------------
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/48411