Narutocc / Vue

:smirk_cat:Vue is a progressive framework for building user interfaces. Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
1 stars 0 forks source link

vue 路由 #32

Open Narutocc opened 6 years ago

Narutocc commented 6 years ago

vue路由

全局钩子:

// 全局钩子
const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: routerConfig
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || 'demo'
  if (!to.query.url && from.query.url) {
    to.query.url = from.query.url
  }
  next()
})

router.afterEach(route => {

})

某个路由独享钩子:

// 某个路由独享钩子
// 给某个路由单独使用,本质上和后面的组件内钩子是一样的,都是特指的某个路由,不同的是,这里一般定义在router当中,而不是在组件内。如下:
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      },
      beforeLeave: (to, from, next) => {
        // ...
      }
    }
  ]
})

路由组件内钩子:

// 路由组件内钩子

beforeRouteEnter (to, from, next) {
  // ...
  next()
},
beforeRouteUpdate (to, from, next) {
  // ...
  next()
},
beforeRouteLeave (to, from, next) {
  // ...
  next()
},
computed: {},
methods: {}

2. 编程式导航

很多按钮在执行跳转之前,还会执行一系列的方法,这时可以使用 this.$router.push(location)来修改url,完成跳转

<button @click="goFirst">登录</button>

methods: {
  goFirst () {
    this.$router.push({path: '/home/first', query: {id: '1'}})
  }
}

或者直接简写

<button @click="$router.push({path: '/home/first', query: {id: '1'}})">登录</button>