Vue-router|青训营笔记

86 阅读1分钟

这是我参与「第四届青训营 」笔记创作活动的第4天

Vue-router

什么是路由?

  • 路由就是SPA(单页应用)的路径管理器,简单来说,vue-router就是我们WebApp的链接路径管理系统。

Vue-router是什么?

  • 由于Vue在开发时对路由支持不足,后来官方补充了vue-router插件,它在Vue的生态环境中非常重要,在实际开发中只要编写一个页面就会操作vue-router。

具体操作

  • 在components里写一个组件hi.vue
  • 在index.js中配置路由
先引入:
import hi from '../components/hi.vue' 
再:
Vue.use(VueRouter) 
最后: 
const routes = [ { path: '/hi', name: 'hi', component: hi }
  • 在APP.vue 模板里需要路由的地方 写(实现基本的跳转)
<router-link to="/hi">hi页面</router-link>

子路由

  • 菜单的路由方式,也叫子路由,子路由的情况一般用在一个页面有它的基础模板,然后它下面的页面都隶属于这个模板,只是部分改变样式。

在具体操作的基础上增加以下操作:

  • 操作详情

    • 在components里写一个组件 例如hi1.vue
    • 在index.js中配置路由
    先引入
    再配置
    const routes = [{
        path: '/hi',
        name: 'hi',
        component: hi,
        children: [
          {path: '/test',name: 'hi',component: hi}, 
          {path: 'hi1',name: 'hi1',component: hi1}, 
          ]
      },]
    
    • 在APP.vue 模板里需要路由的地方 写
    <router-link to="/hi/hi1">hi1页面</router-link>
    

参数传递

  • 用name 传递参数

第一步设置:index.js中配置路由中写name

第二步接收:用{{$route.name}}接收参数(如果有子路由的,name写在子路由里)

  • 路由第二种传参方式

第一步:在APP.vue中写:

<router-link :to="{name:'hi1',params:{username:'xxx',id='xxx',...}}">hi1页面</router-link>
//name值与index.js里配置的值一致

第二步:接收

{{$route.params.username}}-{{$route.param.id}}

单页面多路由区域操作—常用

  • 作用:可把页面分割多个路由区域

第一步:在components文件夹里写组件a,b

第二步:在APP.js里写

<router-view name=”xxx”></router-view>
<router-view name=”yyy”></router-view>

第三步:在index.js文件中router中的components中以对象方式进行配置组件

const routes = [{ path: '/hi', name: 'hi', components:{ xxx=b, yyy=a, } },]