vue路由

111 阅读1分钟

路由信息对象

  • 一个路由对象(route object)表示当前激活的路由的状态信息,包含了当前URL解析得到的信息,还有还有URL匹配到的路由记录(route records)。
  • 路由对象是不可变的,每次成功的导航,都会产生一个新的对象
  • 路由对象出现在多个地方
  • 在组件内,即this.$route
  • 在$route观察者回调内

路由信息对象的属性

  • $route.path
    • -类型:string
    • -字符串,对应当前路由的路径,总是解析为绝对路径,如'.foo/bar'
  • $route.params
    • 类型object
    • 一个key/value对象。包含了动态片段和全匹配片段,如果没有路由参数,就是一个空对象
  • $route.quey
    • 类型object
    • 表示url查询参数
  • $route.hash
    • 类型string
    • 当前路由的hash值(带#)如果没有hash值,则为空字符串
  • $route.name
    • 当前路由的名称,如果有的话(查看命名路由)
  • $route.redirectedFrom
    • 如果存在重定向,即为重定向来源的路由的名字
  • $route.matched
    • 一个数组,包含当前路由的所有嵌套路径片段的路由记录

路由例子

router.js
//1、安装引入
import Vue from "vue";
import VueRouter from "vue-router";
//2、用vue的use方法链接路由对象
Vue.use(VueRouter);
//3、创建UI组件(如果是单文件组件,直接引入)
const Foo={
    template:'<div>Foo</div>'
}
const Bar={
    template:'<div>Bar</div>'
}
//4、创建路由信息并放在路由对象里(也可以直接在路由对象里写)
const routes=[
    {path:'/foo',component:Foo},
    {path:'/bar',component:Bar}
]
const router=new VueRouter({routes:routes})
export default router;
index.js
import router from './router';
new Vue({
  el:"#app",
  router,
  data:{}
  })
index.html
    <hr/>
        <router-link to="/foo">this is Foo</router-link>
        <router-link to="/bar">this is Bar</router-link>
    <hr>
    <router-view></router-view>

路由传值

router.js
//3、创建UI组件(如果是单文件组件,直接引入)
const Foo={
    template:'<div>Foo-{{$route.params.names}}</div>'
}
const Bar={
    template:'<div>Bar</div>'
}
//4、创建路由信息并放在路由对象里(也可以直接在路由对象里写)
const routes=[
    {path:'/foo',component:Foo},
    {path:'/foo/:names',component:Foo},
    {path:'/bar',component:Bar},
]
index.html
<ul>
      <li><router-link to="/foo">this is Foo</router-link>
          <ul>
            <li><router-link to="/foo/jerry">this is jerry</router-link></li>
            <li><router-link to="/foo/tom">this is tom</router-link></li>
          </ul>
      </li>
      <li><router-link to="/bar">this is Bar</router-link></li>
    </ul>
    <hr>
    <router-view></router-view>

路由嵌套

是在路由的所有嵌套路径片段的路由记录。路由记录就是routes配置数组中的对象副本(还有在children数组)

例子
const router = new VueRouter({
    routes:[
        //下面是的对象就是路由记录
        {path:'/foo',component:Foochildren:[
            //这个也是路由记录
            {path:'bar',component;Bar}
        ]}
    ]
})
//当URL为/foo/bar,$route.matched将会是一个从上到下的所有对象(副本)

实例

//3、创建UI组件(如果是单文件组件,直接引入)
const Foo={
    template:'<div><h2>Foo-{{$route.params.names}}</h2><router-view></router-view></div>'
}
const Bar={
    template:'<div>Bar</div>'
}
//创建子组件
const Tom={
    template:'<div>tom</div>'
}
const Jerry={
    template:'<div>jerry</div>'
}
//4、创建路由信息并放在路由对象里(也可以直接在路由对象里写)
const routes=[
    {path:'/foo',component:Foo},
    {path:'/foo/:names',component:Foo,
    children:[
        {path:'',component:Jerry},
        {path:'/tom',component:Tom}
    ]
    },
    {path:'/bar',component:Bar},
    
]