VueJS如何在守卫之前注册全球(VueJS how to register global before guards)
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); }beforeEach hook for every route like in the docs: My page should scroll to the top on route change.
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { window.scrollTo(0, 0) next(); })but my router has another structure and its not working:
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 }, ] })Thanks in advance =) Or is it better to use the .created hook on the components to scroll to the top of the page?
created() { window.scrollTo(0, 0); }最满意答案
您可以将代码调整为文档中所需的结构:
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Contact from '@/components/Contact' Vue.use(Router) // create object router with the valid initialization let router = new Router({ routes: [{ path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/kontakt', name: 'Contact', component: Contact }, ] }); // add the beforeEach hook router.beforeEach((to, from, next) => { window.scrollTo(0, 0); next(); }); // export router as default export default router;You can adapt your code to the structure required in the docs:
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Contact from '@/components/Contact' Vue.use(Router) // create object router with the valid initialization const router = new Router({ routes: [{ path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/kontakt', name: 'Contact', component: Contact }, ] }); // add the beforeEach hook router.beforeEach((to, from, next) => { window.scrollTo(0, 0); next(); }); // export router as default export default router;
更多推荐
发布评论