Vue-Router既不观看路线也不导航护卫射击

pro*_*uri 1 vue.js vue-router vuejs2

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

同样,mycomponent中的beforeRouteUpdate也不会触发。

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

应用程序

<template>
  <router-view></router-view>
</template>
<script>
import Vue from 'vue'
export default {
  name: 'app'
}
</script>
Run Code Online (Sandbox Code Playgroud)

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
        }
]}]})
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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}})
  })
},
...
Run Code Online (Sandbox Code Playgroud)

小智 5

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

MainRouterView.vue

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

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

router.js

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

但是,如果您想坚持自己的结构并检查当前路线的状态,则可以替换beforeRouteUpdatebeforeRouteEnter或替换beforeRouteLeave为该组件。您也可以beforeEach在路由器中使用全局防护。

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