VueJS如何在守卫之前注册全球

时间:2018-01-12 16:11:00

标签: vuejs2 vue-router

in the docs之类的每条路线的beforeEach挂钩: 我的页面应该在路线更改时滚动到顶部。

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
   window.scrollTo(0, 0)
      next();
})

但是我的路由器有另一种结构而且它无法正常工作:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Contact from '@/components/Contact'

Vue.use(Router)

export default new Router({

  beforeEach: (to, from, next) => {
    window.scrollTo(0, 0)
    next();
  },

  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/kontakt',
      name: 'Contact',
      component: Contact
    },
  ]
})

提前致谢=) 或者最好使用组件上的.created钩子滚动到页面顶部?

  created() {
    window.scrollTo(0, 0);
  }

2 个答案:

答案 0 :(得分:4)

您可以根据the docs所需的结构调整代码:

nginx -v
nginx version: nginx/1.13.7

docker --version
Docker version 17.12.0-ce, build c97c6d6

cat nginx.conf
user       www-data;  ## Default: nobody
worker_processes  auto;
pid        /run/nginx.pid;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  include    mime.types;
  default_type application/octet-stream;
  sendfile     on;
  tcp_nopush   on;
  server {
          listen 80;
          listen 443 ssl;
          ssl_certificate     /ssl/nginx.key;
          ssl_certificate_key /ssl/nginx.crt;

          root /web/phabricator/webroot;
          index index.html index.htm index.php;

          server_name _;

          location / {
            index index.php;
            rewrite ^/(.*)$ /index.php?__path__=/$1 last;
          }

          location ~ \.php$ {
            fastcgi_pass   php:9000;
            fastcgi_index   index.php;

            #required if PHP was built with --enable-force-cgi-redirect
            fastcgi_param  REDIRECT_STATUS    200;

            #variables to make the $_SERVER populate in PHP
            fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
            fastcgi_param  QUERY_STRING       $query_string;
            fastcgi_param  REQUEST_METHOD     $request_method;
            fastcgi_param  CONTENT_TYPE       $content_type;
            fastcgi_param  CONTENT_LENGTH     $content_length;

            fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;

            fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
            fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

            fastcgi_param  REMOTE_ADDR        $remote_addr;
    }
  }
}

答案 1 :(得分:0)

我认为你应该在创建路由器之后放置Router.beforeEach。