親バカエンジニアのナレッジ帳

webのエンジニアをやっており、日頃の開発で詰まったことや書き残しておきたいことを載せています。

VueやNuxtで消えないdefault child route のWARNING

routerでchildrenを設定していると表示されるWARNING

VueやNuxtでは、routerの設定でchildrenを使うと構造的に見やすいルーティングを生成できますよね。
ただし、以下のような一件問題なさそうなルーティングを書いた場合、WARNINGが表示されてしまいます。

routes: [{
  path: "",
  component: ParentComponent,
  name: ParentComponent
  children: [{
    path: "",
    component: ChildComponentA,
    name: "ChildComponentA"
  }, {
    path: "b",
    component: ChildComponentB,
    name: "ChildComponentB"
  }]
}]
Named Route 'ParentComponent' has a default child route.
When navigating to this named route (:to="{name: 'ParentComponent'"), the default child route will not be rendered.
Remove the name from this route and use the name of the default child route for named links instead.

これ何が悪いかわかりますか?
エラーではなくあるまでWARNINGなので、このままでも問題ないです。
ただ延々と出続けるのがうるさい…

不要なname設定

では上記のルーティングの設定で「path: ""」にあたるURLにアクセスしてみるとします。
つまりは「http://ドメイン名/」ですね。
ChildComponentAのコンポーネントにあたるページが表示されますが、この時親のコンポーネントのnameと子(children)のコンポーネントのnameのどちらが$route.nameとして適用されるかわかりますか?

はい、子のコンポーネントのnameですね。
そうじゃないとどのページを開いても、$route.nameは全部親のコンポーネントのnameとなってしまいます。

ということで、親のコンポーネントのnameが使われないのに設定されている状態になっており、それが原因でWARNINGが出ているのです。
よって解決策としては以下のように親コンポーネントのnameを削除してしまえば問題ないです。

routes: [{
  path: "",
  component: ParentComponent,
  children: [{
    path: "",
    component: ChildComponentA,
    name: "ChildComponentA"
  }, {
    path: "b",
    component: ChildComponentB,
    name: "ChildComponentB"
  }]
}]