【问题标题】:Vue.js vue-router issue using navigation guard使用导航防护的 Vue.js vue-router 问题
【发布时间】:2017-10-27 07:39:09
【问题描述】:

我正在尝试在我的路由器中使用导航防护...当我使用它时,会显示 App 组件(导航标题)但不显示子主页组件...如果我摆脱导航防护,没问题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

ma​​in.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>

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    您忘记添加next()

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

    【讨论】:

    • 哇.. 非常感谢.. 完全忘记了... 即使在阅读了文档之后... 我剪切/粘贴它并删除了一些我打算稍后添加的其他守卫.. 并忘记了放回下一个()!
    • 干杯伙伴。我们随时为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 2019-08-31
    • 2023-03-09
    • 2021-01-23
    • 2019-09-22
    • 2020-07-14
    • 2021-03-24
    • 2019-04-01
    相关资源
    最近更新 更多