vue-router既没有观看路线也没有看到导航警卫

时间:2018-02-04 01:45:06

标签: vue.js vuejs2 vue-router

在单页应用程序中使用vue-router并使用下面的代码,watch $ route函数在重定向到mycomponent时不会触发。

mycomponent中的beforeRouteUpdate也没有触发。

如何在组件加载期间检测变量何时被标记到路径上?

App.vue

<template>
  <router-view></router-view>
</template>
<script>
import Vue from 'vue'
export default {
  name: 'app'
}
</script>

index.js

import Vue from 'vue'
import Router from 'vue-router'
import MyView from '@/views/MyView'
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/home',
      name: 'Home',
      children: [
        {
          path: '/mycomponent',
          name: 'MyComponent',
          component: MyComponentView
        },
        {
          path: '/mycomponent/:id',
          component: MyComponentView,
          props: true
        }
]}]})

mycomponent.vue

<template>
  <component :is="activeComponent" :id="id"></component>
</template>

<script>
  export default {
    name: 'MyComponentView',
    components: {
      ...
    },
    mounted: function() {
      #this logs path in browser
      console.log('>>mounted route: ' + this.$route.path)
    },
    watch: {
      '$route': function () {
        #this does not fire
        console.log('route watcher: ' + this.$route.path)
      }
    },
    beforeRouteUpdate (to, from, next) {
      #this does not fire
      console.log('>>beforeRouteUpdate')
    },
    data () {
      return {
        activeComponent: 'somecomponent'
      }
    }
  }
</script>

component1.vue

...
mounted: function() {
  Event.$on('vue-tables.row-click', function(data) {
    #this logs correct information in browser
    console.log('data.row.id: ' + data.row.id)
    router.push({path: 'mycomponent', query: {id: data.row.id}})
  })
},
...

1 个答案:

答案 0 :(得分:3)

它不起作用,因为beforeRouteUpdate在要重新加载的组件中(查看Vue的生命周期)。当您更改路线时,watch&amp; beforeRouteUpdate已终止,您将看不到任何结果。在这种情况下,您应该提供以下内容:

MainRouterView.vue

<template>
  <router-view/>
</template>

<script>
  name: 'MainRouterView',
  beforeRouteUpdate (to, from, next) {
    console.log('beforeRouteUpdate')
  },
</script>

router.js

export default new Router({
  routes: [
    {
        {
          path: '/mycomponent',
          name: 'MainRouterView',
          component: MainRouterView,
          children: [
            {
              path: '/mycomponent/:id',
              component: SecondComponent,
            }
          ]
        },
      }]})

但是,如果您想了解结构并检查当前路线的状态,可以将beforeRouteUpdate替换为组件中的beforeRouteEnterbeforeRouteLeave。您也可以在路由器中使用全局防护beforeEach

要更好地了解beforeRouteUpdate的工作原理,请查看以下代码段:http://jsfiddle.net/yraqs4cb/