7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue/Nuxtで`is-active`みたいなclassを条件によって追加しようとしたら'v-bind' directives require an attribute value.と出る件

Posted at

小ネタ。特に

  • NuxtでESLintを有効にし
  • CSSフレームワークをBulmaにして(is-activeとかのclass名をよく使うため)
  • ハイフン付きのis-activeとかのclassを 条件によって追加しようとすると

遭遇しやすいです。

require an attribute value. って言われてもわかりづらいよ!

Vue/Nuxtで条件によってHTMLのclassを動的に変更したい場合、 Vue.jsのドキュメント で紹介されていますが、

「HTMLクラスのバインディング」の例
<div v-bind:class="{ active: isActive }"></div>

そのとおりに is-active などのclassを追加しようとする次のエラーが発生します。

'v-bind' directives require an attribute value.

v-bindで失敗する例
<template>
  <div 
    :class="{ is-active: isDropdownShown }"
    class="dropdown" 
  >
...
</div>
</template>

「attribute valueを設定したはずなのにどうして…🤔」と考えてしまうとハマり始めます。

解決法: 追加しようとするクラス名をシングルクォーテーションで囲む

これだけです。class名に - が含まれている場合、そのままだとattribute valueとして認識されません。

追加しようとするクラス名をシングルクォーテーションで囲む
<template>
  <div 
    :class="{ 'is-active': isDropdownShown }"
    class="dropdown" 
  >
...
</div>
</template>

JavaScriptの識別子…Objectのkey…と考えると気づきやすいですね!

7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?