Vue Router基础

路由

安装 vue-router

起步

<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>

<router-view></router-view>
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }


const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})


const app = new Vue({
  router
}).$mount('#app')

通过this.$route访问路由器

export default {
  computed: {
    username () {
      return this.$route.params.username
    }
  },
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}

动态路由

{ path: '/user/:id', component: User }

像/user/bar和/user/foo都能映射到相同的路由

参数会被设置到this.$route.params中

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

可以设置多端参数

// 模式
/user/:username/post/:post_id
// 匹配路径
/user/evan/post/123
// $router.params    
{ username: 'evan', post_id: '123' }

从/user/foo到/user/bar 原来的组件实例会被复用。因为两个路由都渲染同一个组件。也就是组件不会销毁和创建,而是复用,也就是组件的生命周期钩子不会再调用

可以使用watch检测$router对象

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // 对路由变化作出响应...
    }
  }
}

捕获所有路由或404 Not found路由

匹配所有路由

path: '*'

匹配'/user-*'开头的路由

path: '/user-*'

当使用通配符时,$router.params会添加名为pathMatch参数

// 给出一个路由 { path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
// 给出一个路由 { path: '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'

嵌套路由  

 我们在User组件中添加router-view

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

路由配置

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})
View Code

编程式导航

声明式 <router-link :to='' />

编程式 router.push()

const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

router.go(n)

// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

// 前进 3 步记录
router.go(3)

// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
View Code
命名路由
const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
})
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
router.push({ name: 'user', params: { userId: 123 }})

命名视图

一个组件渲染多个视图

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

重定向

/a重定向到/b

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})

也可以是命名路由

 { path: '/a', redirect: { name: 'foo' }}

也可以是方法

 { path: '/a', redirect: to => {
      // 方法接收 目标路由 作为参数
      // return 重定向的 字符串路径/路径对象
    }}

别名

{ path: '/a', component: A, alias: '/b' }

路由组件传参

之前我们通过$router获得参数

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})
View Code

通过props解耦

如果props设置为true,那么route.params将会被设置为组件属性

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})
原文地址:https://www.cnblogs.com/sonwrain/p/10805511.html