使用导航防护的Vue.js vue-router问题

时间:2017-10-27 07:39:10

标签: vue.js vue-router

我正在尝试使用我的路由器导航警卫...当我使用它时,显示应用程序组件(导航标题)但不显示子主页组件...如果我摆脱了导航警卫,没问题App和HomePage组件显示良好

在这种情况下我的导航防护用途有什么问题?

路由器/ index.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/HomePage'
import ShoppingLists from '@/pages/ShoppingListsPage'

Vue.use(Router)

const router = new Router({
  // HTML5 mode history
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: { title: 'Home' }
    },
    {
      path: '/shoppinglists',
      name: 'ShoppingLists',
      component: ShoppingLists,
      meta: { title: 'Shopping Lists' }
    }
  ]
})

router.beforeEach(function (to, from, next) {
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }
})

export default router

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

/* eslint-disable no-new */
new Vue({
  el: 'app',
  router,
  components: { App }
})

App.vue

<template>
  <div id="app">
    <ul class="navigation">
      <li id="home"><router-link :to="{ name: 'Home' }" >Home</router-link></li>
      <li id="shoppinglists"><router-link :to="{ name: 'ShoppingLists' }" >Shopping Lists</router-link></li>
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

HomePage.vue

<template>
  <div class="hello">
    <img src="./../assets/logo.png">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'Hello',
  data () {
    return {
      msg: 'Welcome to our ShoppingList app'
    }
  }
}
</script>

的index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>shopping-list</title>
  <link rel="shortcut icon" type="image/png" href="/static/favicon.ico"/>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <app></app>
  <!-- built files will be auto injected -->
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您忘记添加next()

router.beforeEach(function (to, from, next) {
  if (to.meta && to.meta.title) {
    document.title = to.meta.title

    next()
  }

  next()
})