Vue路由篇--基础篇

Vue路由篇–基础篇

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

首先要引入这两个js文件,如果不下载的话 可以直接script引入,建议下载保存到本地引入,这样快些
下面是代码以及注释,注释都是自己理解,比较容易懂

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../../vue.js"></script>
    <script src="../../vue-router.js"></script>
    <style>
        .active{
            font-size: 20px;
            color:red
        }
    </style>
</head>
<body>
    <div id="app">
        <ul>
            <!-- tag属性默认是a标签,手动修改就像如此,可以修改成li -->
            <!-- to属性是路径,就是你接下来点击要跳转到哪里 -->
            <!-- active-class属性就是点击选中的样式,上面style中设置的就是这里用到的 -->
          <router-link tag='li' to='/' exact active-class="active">首页</router-link>  <!-- exact精确匹配可以解决首页和职位同时选中样式 -->
          <router-link tag='li' to='/position' active-class="active">职位</router-link>  <!-- 路由要进行跳转  router-link作为跳转标签 -->
          <router-link tag='li'to='/search' active-class="active">搜索</router-link>  
        </ul>
          <router-view></router-view> <!-- 链接的内容视图,只要跟router-link平级  就会把router-link的内容放在router-view里面 -->   
    </div>
    <script>
        const position={//局部组件的定义
            template:`<div>position</div>`//模板
        }
        const search={
            template:`<div>search</div>`
        }
        const index={
            template:`<div>index</div>`
        }
        
        var router=new VueRouter({//VueRouter的实例
            mode:'hash',//默认是哈希   也可以配history  
            routes:[{//固定的格式
                path:'/position',//path就是路径
                component:position//注册组件
            },{
                path:'/search',
                component:search
            }
            ,{
                path:'/',
                component:index
            }]
        })
        var vm=new Vue({
            router:router,//router=new好VueRouter的实例  这里可以简写成router
            el:"#app"
        })
    </script>
</body>
</html>

展示效果
注意地址栏所用的是hash模式
在这里插入图片描述

发布了8 篇原创文章 · 获赞 6 · 访问量 2370

猜你喜欢

转载自blog.csdn.net/tianlei11/article/details/105340384