Router 构建选项

1. routes

类型: Array
RouteConfig 的类型定义:

declare type RouteConfig = {
  path: string;
  component?: Component;
  name?: string; // 命名路由
  components?: { [name: string]: Component }; // 命名视图组件
  redirect?: string | Location | Function;
  props?: boolean | Object | Function;
  alias?: string | Array;
  children?: Array; // 嵌套路由
  beforeEnter?: (to: Route, from: Route, next: Function) => void;
  meta?: any;

  // 2.6.0+
  caseSensitive?: boolean; // 匹配规则是否大小写敏感?(默认值:false)
  pathToRegexpOptions?: Object; // 编译正则的选项
}

 

2. scrollBehavior 属性:控制页面滚动到具体位置

const router = new VueRouter({
  routes: [...],
  // 滚动行为 这个功能只在支持 history.pushState 的浏览器中可用(IE9)
  scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    const position = {};
    // 返回 savedPosition,在按下 后退/前进 按钮时,就会像浏览器的原生表现那样
    if (savedPosition) {
      return savedPosition;
    } else if (to.hash) {
    // 模拟“滚动到锚点”的行为
      position.selector = to.hash;

      // specify offset of the element
      if (to.hash === '#anchor2') {
        position.offset = { y: 100 };
      }

      if (document.querySelector(to.hash)) {
        return position;
      }

      // if the returned position is falsy or an empty object,
      // will retain current scroll position.
      return false;
    } else {
    // 其他滚动
      
      // 正常的滚动到顶部
      // return { x: 0, y: 0 };

      // 导步延迟滚动
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     resolve({ x: 0, y: 0 });
      //   }, 500);
      // });
      
      // 异步滚动
      return new Promise(resolve => {
        // check if any matched route config has meta that requires scrolling to top
        if (to.matched.some(m => m.meta.scrollToTop)) {
          // coords will be used if no selector is provided,
          // or if the selector didn't match any element.
          position.x = 0;
          position.y = 0;
        }
  
        // wait for the out transition to complete (if necessary)
        this.app.$root.$once('triggerScroll', () => {
          // if the resolved position is falsy or an empty object,
          // will retain current scroll position.
          resolve(position);
        })
      });
    }
  },
});

你可能感兴趣的:(Router 构建选项)