vue简易路由的原理

at 2023.05.06 23:22  ca Vue.js  pv 1365  by yanjun202  

 需要实现两个功能

    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 

分享到:

 

扫一扫在手机阅读、分享本文

已有1条评论