vue-router

97 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

1. vue-router

Vue Router是Vue.js的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。功能包括:

  • 嵌套路由映射
  • 动态路由选择
  • 模块化、基于组件的路由配置
  • 路由参数、查询、通配符
  • 展示由 Vue.js 的过渡系统提供的过渡效果
  • 细致的导航控制
  • 自动激活 CSS 类的链接
  • HTML5 history 模式或 hash 模式
  • 可定制的滚动行为
  • URL 的正确编码

命令行创建vue文件步骤:

  1. 创建vue文件vue init webpack +vue文件名

  2. 进入工程目录cd myvue

  3. 安装vue-routernpm install vue-router --save-dev

  4. 安装依赖npm install

  5. 安装SASS加载器cnpm install sass-loader node-sass --save-dev

  6. 启动测试npm run dev

文件结构如下:

image.png

在router下的index.js

// 主配置文件
import Vue from 'vue/'
import VueRouter from 'vue-router'
import Content from '../components/Content'
import Main from '../components/Main'

// 安装路由
Vue.use(VueRouter)

// 配置导出路由
export default new VueRouter({
  routes: [
    {
      // 路由路径
      path: '/content',
      name: 'content',
      // 跳转的组件
      component: Content
    },
    {
      // 路由路径
      path: '/main',
      name: 'main',
      // 跳转的组件
      component: Main
    }
  ]
})

在Content.vue中

<template>
<h1>内容页</h1>
</template>

<script>
export default {
  name: 'Content'
}
</script>

<style scoped>

</style>

同样,在Main.vue中

<template>
<h1>首页</h1>
</template>

<script>
export default {
  name: 'main'
}
</script>

<style scoped>

</style>

实现效果如下: image.png

点击下方的首页后实现跳转页面 image.png

点击下方的内容页后实现跳转页面 image.png

2. 路由嵌套

在views下新建main.vue等文件,如下图所示

image.png

在main.js中写

import Vue from 'vue'

import Router from 'vue-router'

import main from '../views/main'

import login from '../views/login'

import UserList from '../views/user/List'

import UserProfile from '../views/user/Profile'

 

Vue.use(Router);

export default new Router({

  routes:[

    {//路由嵌套

      path:'/main',

      component:main,//嵌套路由

      children:[

        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile},

        {path:'/user/list',component:UserList}

      ]

    },{

      path:'/login',

      component:login

    }

  ]

});

方法1:

在vue中绑定

name 传组件名,params 传递参数,需要对象v-bind

<router-link v-bind:to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

在index.js中绑定path

children:[

        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile},

        {path:'/user/list',component:UserList}

      ]

在目标文件绑定

<template>

<!--  template的下一级面只能有一个标签-->

  <div>

    <h1>个人信息</h1>

    {{$route.params.id}}

  </div>

</template>

 

方法2:

Vue不变

在index.js中绑定path

children:[

        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},

        {path:'/user/list',component:UserList}

      ]

在目标文件绑定

<template>

<!--  template的下一级面只能有一个标签-->

  <div>

    <h1>个人信息</h1>

    {{id}}

  </div>

</template>

<script>

export default {

  props:['id'],

  name: "Profile"

}

</script>