Vue路由的使用

路由即:浏览器URL中的哈希值(# hash)与展示视图内容(template)之间的对应规则
路由就是一套映射规则(一对一的对应规则),由开发人员制定规则。
当URL中的哈希值(# hash)发生改变后,路由会根据制定好的规则,展示对应的视图内容

<style>
  /* 路由高亮,自动添加样式在此页面的链接导航上 */
  .router-link-exact-active,
  .router-link-active {
    color: yellowgreen;
    font-size: 30px;
  }
</style>

<body>
  <!-- 0.安装:`npm i -S vue-router` -->
  <div id="app">
    <!-- 5 链接导航 -->
    <router-link to="/home">首页</router-link>
    <router-link to="/login">登录</router-link>
    <!-- 6 路由出口:用来展示匹配路由视图内容 -->
    <router-view></router-view>
  </div>
  <!-- 1 导入 vue.js -->
  <script src="./vue.js"></script>
  <!-- 2 导入 路由文件 -->
  <script src="./node_modules/vue-router/dist/vue-router.js"></script>
  <script>
    // 3 创建两个组件
    const Home = Vue.component('home', {
      template: '<h1>这是 Home 组件</h1>'
    })
    const Login = Vue.component('login', {
      template: '<h1>这是 Login 组件</h1>'
    })

    // 4 创建路由对象
    const router = new VueRouter({
      //配置路由规则
      // path 是路由规则,用来与浏览器地址栏中的哈希值进行匹配
      // component 用来值该规则匹配后,要展示到页面中的组件内容
      routes: [
        { path: '/', redirect:'/home' },//路由的重定向 将 `/` 重定向到 `/home`
        { path: '/home', component: Home },
        { path: '/login', component: Login }
      ],
       // 通过配置项 `linkActiveClass: 'now'` 来修改默认的高亮类名
       linkActiveClass: 'active'
    })

    var vm = new Vue({
      el: '#app',
      // 将路由与vue实例关联到一起!
      router
    })
  </script>
</body>

嵌套路由

// 父组件:
const User = Vue.component('user', {
  template: `
    <div class="user">
      <h2>User Center</h2>
      <router-link to="/user/profile">个人资料</router-link>
      <router-link to="/user/posts">岗位</router-link>
      <!-- 子路由展示在此处 -->
      <router-view></router-view>
    </div>
    `
})
// 子组件:
const UserProfile = {
  template: '<h3>个人资料:张三</h3>'
}
const UserPosts = {
  template: '<h3>岗位:FE</h3>'
}
//配置路由规则
 routes: [
   { path: '/user', 
     component: User,
  // 子路由配置:
    children: [
    {
      // 当 /user/profile 匹配成功,
      // UserProfile 会被渲染在 User 的 <router-view> 中
      path: 'profile',
      component: UserProfile
    },
    {
      // 当 /user/posts 匹配成功
      // UserPosts 会被渲染在 User 的 <router-view> 中
      path: 'posts',
      component: UserPosts
    }
 ]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值