〖Vue〗必备小知识- 前端路由 hash模式解析

1,300 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前文我们简单学习了 Vue-Router 的初步使用, 及实现一个今天来具体学习一下 Vue 项目小实战之页面切换: 路由 Vue-Router

Vue-Router 前端路由 的具体使用

前后端 路由的区别

后端路由 根据不同的 url 返回不同的内容

前端路由 根据不同的 hash 值,切换不同的组件

hash 模式代码实现

监听 hashchange变化进行对应的路径处理

<html>
    <head>
        <meta charset="utf-8" />
        <title>前端路由 hash模式解析</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.js"></script>
    </head>
    
    <body>
        <a href="#/page-one">page-one</a>
        <a href="#/page-two">page-two</a>
        <a href="#/page-three">page-three</a>
        <div id="box"></div>
    </body>
    
    <script>
        const routes = [
            {
                path: '/page-one',
                component: './template/one.html'
            },
            {
                path: '/page-two',
                component: './template/two.html'
            },
            {
                path: '/page-three',
                component: './template/three.html'
            },
        ]
        
        let hash = location.hash // 获取 hash 值
        if(!hash) {
            location.hash = '#/one' // 默认设置 hash值为 '#/one'
        }
        hash = location.hash.replace('#', '') // 去掉hash当中的 '#'号
        let cache = {} // 用作缓存
        window.addEventListener('hashchange', () => {
            hash = location.hash.replace('#', '')
            routes.forEach(item => {
                if(item.path === hash) {
                    if(cache[hash]) { // 如果缓存中存在访问过的对象, 就用缓存里的对象
                        $('#box').html(cache[hash])
                    }
                } else {
                    $.ajax(item.component).then(res => {
                        $('#box').html(res)
                        cache[hash] = res
                    })
                }
            })
        })
    </script>
</html>

路由的使用和路由的重定向和404页面如何做

子路由的使用 children

  • exact 精确匹配的时候样式才会应用上

path

路由传参

  1. this.$route.params.id]

  2. props

  3. <router-link :to={'name':名字:params:{键值对....}}

import axios from "axios"
Vue.prototype.axios=axios;

只要在入口文件里使用一次即可 其他组件用

this.$http.get

切换路由参数的时候,组件不会卸载

但是,切换路由组件的时候,组件会卸载

const routes: [
    {
      path: 'pageone',
      component: './template/PageOne.html',
    },
    {
      path: 'pageone',
      component: './template/PageTwo.html',
    },
    {
      path: 'pageone',
      component: './template/PageThree.html',
    },
  ],

路由传参

第一种 this.$route.params.id 第二种 props

第三种