LoginSignup
2
0

More than 3 years have passed since last update.

【Vue.js】Component template requires a root element, rather than just text.

Last updated at Posted at 2020-04-22

書いたコード概要とエラー

私が開発していた箇所では、HTML内のテンプレート・コンポーネントを作成するJavascriptに分けてVueコンポーネントのコードを記述していました。

HTML

<script id="someComponent" type="text/x-template">
  <div>
    ...
  </div>
</script>

Javascript

Vue.component('some-component', {
  // ...
  template: 'someComponent'
});

前例に倣ったつもりでこのように書いたところ、該当のコンポーネントを表示させる処理を実行した時、想定していた要素が表示されず、代わりにコンソールにエラーが出力されました。

エラー

[Vue warn]: Error compiling template:
someComponent
- Component template requires a root element, rather than just text.

原因

エラーメッセージだけ見て不可解に思っていましたが、処理的にはid="someComponent"となっている要素を読み込むのではなく、someComponentという文字列をテンプレートとして解釈しようとしていたことが分かりました。気づいてみれば当然といえば当然ですね……。

修正後

Javascript

Vue.component('some-component', {
  // ...
  template: '#someComponent'
});

このように書くことで、無事id="someComponent"となっている要素の内容をコンポーネントとして読み出し、表示することができました。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0