简易路由history原理

history主要是通过pushState和replaceState去重写url路径实现单页面路由切换

通过window.onpopState去监听前进后退的路径

简易式步骤:

//创建三个组件引入
import Home from './components/Home.vue'
import Login from './components/Login.vue'
import User from './components/User.vue'

//创建路由规则表
const routes = [
{path:'/home',component:Home},
{path:'/login',component: Login},
{path:'/user',component: User}
]

//shallowRef只会给最外层做数据劫持
const current = shallowRef()

const push = (url:string)=>{
console.log(url)
history.pushState(null,'',url)
current.value = routes.find(item => item.path === url)?.component
}


//监听history 的前进后退切换组件
window.onpopState = ()=>{
    current.value = routes.find(item => item.path ===localtion.pathname)?.component
}

//html
<button @click="push('/home')">首页</button>
<button @click="push('/login')">登陆</button>
<button @click="push('/user')">个人中心</button>

猜你喜欢

转载自blog.csdn.net/shmilynn_/article/details/129171727
今日推荐