vue简易路由的原理

君哥 阅读:1901 2023-05-06 23:22:49 评论:1

 需要实现两个功能

    1、路径变化组件跟着变化

    2、浏览器可以前进后退,组件变化


关键点:

    1、vue 内置的动态组件 绑定 is 属性绑定组件名称

    2、自定义路由规则,让url和组件名称一一对应

    3、使用history.pushState(),第三个参数让url改变,同时改变url对象的组件名称

    4、window.onpopstate(),点击浏览器的前进按钮/后退按钮触发的事件,获取到loction.pathname 来改变组件名称


代码参考如下:


// url 变化 组件变化
// 前进后退 组件变化
// 首先自己新建 三个组件
import HomeVue from './views/components/HomeVue.vue'
import LoginVue from './views/components/LoginVue.vue'
import UserVue from './views/components/HomeVue.vue'
import { shallowRef } from 'vue'
const routes = [
  { path: '/home', component: HomeVue },
  { path: '/login', component: LoginVue },
  { path: '/user', component: UserVue }
]
const currentPage = shallowRef()
const push = (url: string) => {
  // console.log(url)
  history.pushState(null, '', url)
  currentPage.value = routes.find((item) => item.path === url)?.component
}
window.onpopstate = () => {
  // console.log(location.pathname)
  currentPage.value = routes.find(
    (item) => item.path === location.pathname
  )?.component
}





本文链接:https://www.yanjun202.com/post/79.html 

分享到:
可以去百度分享获取分享代码输入这里。
发表评论
搜索
排行榜
关注我们

扫一扫关注我们,了解最新精彩内容