Vue_小白个人学习历险记_Vue-router

87 阅读1分钟

Vue-router工作原理

单页面应用(SPA)核心思想,更新视图而不重新请求页面

实现单页面前端路由时,提供了两种方式:hash(默认)/history两种模式

  1. hash模式:使用URL的hash来模拟一个完整的URL,当URL发生改变时,页面不会重新加载。#是hash符(哈希符/锚点),该符号后的值为hash值

  2. history模式:利用history.pushState()来完成URL的页面跳转而且无须重新加载页面。history新增API,'history.pushState()和history.replaceState',都包含三个参数{状态对象state object,标题 title,地址 URL}

image.png

image.png

Vue-router三部曲

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue-router三部曲</title>
<!--  注:这里需要引入vue.js官网下载的vue.js/vue-router.js两个文件  -->
<!-- 1,引包   -->
    <script src="lib/vue.js"></script>
    <script src="lib/vue-router.js"></script>
</head>
<body>
<div id="app">
    <router-link to="/login">登录</router-link>
    <router-view></router-view>
</div>
<template id="login">
    <h1>我是登录组件</h1>
</template>
<script>
    //4,定义子组件
    var Login = {
        template:'#login'
    }
    //3,定义VueRouter实例
    var router = new VueRouter({
        routes:[
            {
                path:'/login',//路径
                component:Login//子组件名
            }
        ]
    })
    var app = new Vue({
        el:'#app',
        data:{

        },
        //2,挂载到Vue实例中
        router
    })
</script>
</body>
</html>