20
12

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.js/Nuxt.js] $refsの命名をする際はキャメルケース、もしくはケバブケースで書かないと動かない

Last updated at Posted at 2019-03-07

環境

Nuxt.js: ^2.0.0

概要

DOMにrefを指定することで、子コンポーネントのプロパティやメソッドに触ることができる。

今回はrefを指定してあるメソッドを実行したかったのだが、なぜかうまく動かなかった。

原因は、refをスネークケース記法で書いていたことだった。(しょうもない)

このデバッグに時間がかかりすぎたのでここに知見を残しておく。

悪い例

スネークケース

<template>
 <div>
   <ComponentSpecial ref="component_special" />
 </div>
</template>
// undefined
console.log(this.$refs.component_special);

パスカルケース

<template>
 <div>
   <ComponentSpecial ref="ComponentSpecial" />
 </div>
</template>
// undefined
console.log(this.$refs.ComponentSpecial);

動く例

キャメルケース

キャメルケースで書くとドット記法でいけるのでおすすめです。

<template>
 <div>
   <ComponentSpecial ref="componentSpecial" />
 </div>
</template>
// undefined
console.log(this.$refs.componentSpecial);

ケバブケース

ケバブケースの場合はブラケット記法で書くと参照できます。

<template>
 <div>
   <ComponentSpecial ref="component-special" />
 </div>
</template>
// undefined
console.log(this.$refs['component-special']);

参考リンク

探してもあまり見つかりませんでした。

vue.js – Vue $refs和烤肉串案 - 代码日志

20
12
1

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
20
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?