Vue生命周期事件在每条路径上触发

时间:2017-08-08 09:51:58

标签: vuejs2 vue-component vue-router

根据文档https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram,应该调用beforeCreatemounted之间的所有事件。但它们是在每个导航的路由器路径上触发的

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  created: function () {
    this.$http.get('/user/get').then(response => {
      if (response.data.error) {
        console.log(response.data.error)
      } else {
        User.set(response.data.user)
        router.go('/dashboard')   // this does force looping
      }
    }, response => {
      router.go('/')
    })
  }
})

这是App.vue

<template>
  <div id="app">
    <topmenu></topmenu>
    <router-view></router-view>
  </div>
</template>

<script>
import Topmenu from '@/components/topmenu'

export default {
  name: 'app',
  components: {
    topmenu: Topmenu
  }
}
</script>

Router.vue

Vue.use(Router)

let route = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/user/signup',
      name: 'Signup',
      component: Signup
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: Dashboard
    }
  ]
})
route.beforeEach((to, from, next) => {
  if (to.path.match(/^(\/|\/signup)$/)) {
    return next()
  }
  if (User.valid()) {
    return next()
  }
  route.push('/')
})
export default route

如何避免在每个路由切换时触发此事件?

0 个答案:

没有答案