vue路由巢狀

GHUIJS發表於2020-12-18

1. vue路由嵌適用套場景

最近自娛自樂用vue做小東西,覺得路由js裡程式碼太亂了,就想著用一下路由巢狀來著。我當時小專案場景類似如下場景(當時場景類似JQ開發時主頁面跳轉子頁面),

但實際路由巢狀是類似jq開發時點選按鈕顯示隱藏效果,還是我做的太少,太天真了,想著主頁面跳轉子頁面也用路由跳轉來著...

場景總結,只有頁面一部分變,一部分不變才合適用路由巢狀。

 2.路由巢狀使用(路由巢狀使用兩個注意點:子路由的path,主元件結構必須加上<router-view></router-view>標籤)

(1).路由path省略寫法(例如下程式碼第一條子路由),也可全寫(例如下程式碼第二條子路由)

{
      path: '/components',
      meta: {
        footShow: true
      },
      component: resolve => require(['../pages/components/components.vue'], resolve),
      redirect:'/components/view',//可讓父級路由重定向展示想要預設顯示的子元件
      children: [{
          path: 'tips',
          component: resolve => require(['../pages/components/components-pages/tips/tips.vue'], resolve),
        },
        {
          path: '/components/view',
          component: resolve => require(['../pages/components/components-pages/view/view.vue'], resolve),
        },
        {
          path: 'tree',
          component: resolve => require(['../pages/components/components-pages/tree/tree.vue'], resolve),
        },
        {
          path: 'video',
          component: resolve => require(['../pages/components/components-pages/video/video.vue'], resolve),
        },
        {
          path: 'viewImage',
          component: resolve => require(['../pages/components/components-pages/viewImage/viewImage.vue'], resolve),
        },
      ]
    }

 (2).必須在主元件合適的地方加<router-view></router-view>標籤,不然子元件不會顯示。

    <div class="ui-pane">
		<navbar v-if="$route.meta.footShow"></navbar>
		<ui-header headertit="元件"><span>抽屜</span></ui-header>
		<div class="ui-content">
			<arealine linetit="原生元件"></arealine>
            <router-view></router-view>
			<pageine linetit="tips" to="/components/tips"></pageine>
			<pageine linetit="view" to="/components/view"></pageine>
			<pageine linetit="viewImage" to="/components/viewImage"></pageine>
			<pageine linetit="tree" to="/components/tree"></pageine>
			<pageine linetit="video" to="/components/video"></pageine>
		</div>
	</div>

(3).路由巢狀中若需要預設顯示 某一子路由時,可以讓父級路由重定向(redirect:'/components/view');

 

相關文章