SPAl路由

前端路由

根据路由对应地址渲染不同的内容

前端的分类

页面路由(刷新)

  • 根据对应的地址访问不同的页面(location.href      location.assign   location.repalce)

 hash 路由(不会刷新)

  • 根据对应的hash 地址来渲染不同的内容(onhashchange)
  • location.hash 来获取对应的hash 值,通过onhashchange 进行监听

history 路由(不会刷新)

  • 根据对应的history 页面的地址来渲染不同(onpopsate)
  • 通过replaceState 和pushState 来改变state 的值和页面的地址
  • 通过history.back  history.go      histoy.forwrd.forward 来触发对应的onpopstate事件

后端

根据对应的路由地址访问对应的接口

SPA

单页应用程序(single  pahge  application),整个应用只有一个页面,那么对应的页面调整就没有意义,所以对应的SPA 的路由实现就主要是hash 模式和 history 模式。在后续的vue 或者是对应的react 中,他主要做的是SPA的应用,那么对应的 主要采用的模式 hash和history,hash 的监听能直接触发而history 的监听不能直接触发,而history 的监听不能直接触发,所以默认的模式就是hash 模式。

Vue中的SPA路由

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./lib/vue.min.js"></script>
    <script src="./lib/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <!-- 路由链接 to指定的地址  router-link会解析成a标签-->
        <router-link to="/">去首页</router-link> 
        <router-link to="/user">去用户页</router-link>
        <!-- 路由视图 显示的视图  router-view会解析你对应需要渲染的内容-->
        <router-view></router-view>
    </div>
    <script>
        //组件 渲染的内容
        let home = Vue.component('home',{
            template:'<div>首页</div>'
        } )
        //渲染的内容
        let user = Vue.component('user',{
            template:'<div>用户页</div>'
        } )
        //路由对象
        let router = new VueRouter({
            //路由配置 router 名词(路由对象)  route 动词(路由配置) routes 多个(路由配置)
            routes:[
                //route规则
                {
                    name:'home',//名字
                    path:'/', //路由地址
                    component:home //组件 渲染什么
                },
                {
                    name:'user',
                    path:'/user',
                    component:user
                }
            ]
        });
        new Vue({
            el:'#app',
            //传入路由配置 router
            router
        })
    </script>
</body>
</html>

 

posted @ 2022-11-10 22:05  後楓浪  阅读(33)  评论(0)    收藏  举报