wumi_blog icon indicating copy to clipboard operation
wumi_blog copied to clipboard

vue-router1.0 用data钩子碰到的...

Open 5Mi opened this issue 8 years ago • 0 comments

项目中碰到在component的template中直接传入一个组件标签的情况,当时想着直接在这里把动态匹配的参数通过props传给切换的组件,但切换路由时此组件里面的route钩子不触发,后来才发现这个:

component:vue.extend()
//与 下面这种的区别了
component:{
    template:'',
    data(){},
    route:{}
}

vue-router

路由配置对象

路由配置对象包含两个字段:

component: 当路径匹配时,会渲染到顶级<router-view>的 Vue 组件。此字段的值可以是调用Vue.extend 后返回的构造函数,或者普通的组件选项对象。在后一种情况下,路由会隐式调用Vue.extend。 subRoutes: 嵌套的子路由映射。对于每一个subRoutes 映射中的子路由对象,路由器在做匹配时会使用其路径拼接到父级路径后得到的全路径。成功匹配的组件会渲染到父级组件的 <router-view>中。

router.map({
  // 组件构造函数
  '/a': {
    component: Vue.extend({ /* ... */ })
  },
  // 组件选项对象
  '/b': {
    component: {
      template: '<p>Hello from /b</p>'
    }
  },
  '/c':{
    component:{
        //如果直接传入一个组件标签 当路由切换时此组件
        //中的 route钩子都不会触发,
        //因为此组件属于切换路由的<router-view></router-view>的子组件
        template:'<somecomponent></somecomponent>'
    }
  },
  // 嵌套的路由
  '/d': {
    component: {
      // 渲染子视图
      template: '<router-view></router-view>'
    },
    subRoutes: {
      // 当路径是 /c/d 时进行渲染
      '/d': { component: { template: 'D' }},
      // 当路径是 /c/e 时进行渲染
      '/e': { component: { template: 'E' }}
    }
  }
})

参考

5Mi avatar Aug 24 '16 10:08 5Mi