vue 路由的基本使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/vue-router.js"></script>
    <style>
        /*.router-link-active{*/
            /*color: red;*/
        /*}*/
        .active{
            color: red;
        }
    </style>

</head>

<body>
<div id="app">
    <router-link to="/home">主页</router-link>
    <router-link to="/news">新闻</router-link>

     <!--显示路由内容-->
    <router-view></router-view>
</div>


</body>

<script>
    // 1.定义组件
    var home = {
        template: '<h1>home</h1>'
    };
    var news = {
        template: '<h1>news</h1>'
    };
    //2. 配置路由
    const routes = [
        {path:'/home',component:home},
        {path:'/news',component:news},
        {path:'*',redirect:'/home'}
    ];

    //3. 配置路由实例
    const router = new VueRouter({
        routes,
        mode:'history',  //切换不同的模式
        linkActiveClass: "active"  //动态类
    });

    //4. 挂载
    new Vue({
        el: "#app",
        router,
    })


</script>
</html>
  1. hash —— 即地址栏 URL 中的 # 符号(此 hash 不是密码学里的散列运算)。
    比如这个 URL:http://www.abc.com/#/hello,hash 的值为 #/hello。它的特点在于:hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面。
  2. history 模式下,前端的 URL 必须和实际向后端发起请求的 URL 一致,如 http://www.abc.com/book/id。如果后端缺少对 /book/id 的路由处理,将返回 404 错误。Vue-Router 官网里如此描述:“不过这种模式要玩好,还需要后台配置支持……所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。”
原文地址:https://www.cnblogs.com/wspblog/p/10109857.html