一文让你理解vue history和hash模式实现
2023-09-27 14:22:16 时间
由于在网上都没有找到关于这两种模式的简单实现,所以自己撸一个:
mode:hash
代码简单实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--宽度为设备宽度,初始缩放比例为 1 倍,禁止用户缩放--> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"> <title>hash-mode-demo</title> <style> html,body{ width: 100%; height: 100%; padding-left: 10px; padding-top: 10px; box-sizing: border-box; } .btn{ width:140px; height:60px; line-height:60px; text-align: center; background: #f60; color:#fff; margin-bottom: 50px; box-shadow: 0 0 7px 7px rgba(0,0,0,0.2); } .content{ line-height: 20px; color:red; font-size: 14px; } </style> </head> <body> <script> //单页面切换监听:触发渲染 window.onhashchange = function(event){ console.log("event.oldURL:",event.oldURL); console.log("event.newURL:", event.newURL); console.log("location.hash:", location.hash); let hash = location.hash.slice(1); render(hash); } //组件路由 const Router = [ { path: '/home', name: 'home', meta: {title: '首页'}, component:` <div class="btn btn1" onclick="location.hash = 'paying'">去-正在支付页</div> <div class="btn btn2" onclick="location.hash = 'productList'">去-商品清单页</div> <div class="btn btn3" onclick="location.hash = 'addAddress'">去-添加收货地址页</div> ` }, { path: '/paying', name: 'paying', meta: {title: '正在支付'}, component:`<div class="content">正在支付内容内容内容内容内容内容</div>` }, { path: '/product-list', name: 'productList', meta: {title: '商品清单'}, component:`<div class="content">商品清单内容内容内容内容内容内容</div>` }, { path: '/add-address', name: 'addAddress', meta: {title: '添加收货地址'}, component:`<div class="content">添加收货地址内容内容内容内容内容内容</div>` } ] //首页渲染 window.location.hash = 'home'; render(); //组件渲染 function render(){ let hash = location.hash.slice(1); Router.forEach(item=>{ if(item.name != hash) return; document.title = item.meta.title; document.body.innerHTML = item.component; }) } </script> </body> </html>
模拟vue单页面应用hash模式切换效果简单实现
相关文章
- (尚002)Vue的基本使用
- 百度地图 创建 自定义控件(vue)
- [转]浅谈vue中provide和inject 用法
- vue 使用jssdk分享
- vue前端性能优化之gzip
- vue cli选择lint模式
- 03-vue基础-组件
- vue.js不仅是一种模式,也是一种工程组织方式
- 一、Vue分页实现
- vue-router模式history与hash
- [WDS] Warnings while compiling. vue项目运行控制台输出太多警告信息
- vue router 的两种路由模式hash与history的区别
- Vue的过滤器、生命周期钩子函数、组件开发、路由、Promise基本使用语法
- Vue.js中this.$nextTick()的使用
- vue组件值传递之父组件向子组件传递(props)
- vue脚手架 环境变量和模式
- 在vue中引入layer弹框的简易方法
- 解决IE报错[vue router]Failed to resolve async component default:strict 模式下不允许分配到只读属性
- vue面试(一)
- Vue学习第34天——路由的2种工作模式:hash和history的区别
- vue用Export2Excel 自动换行
- 从零写一个类似Vue的Mvvm框架 01