LoginSignup
4
2

More than 5 years have passed since last update.

Vue.jsでコンポーネントのイベント名をキャメルケースにすると反応しない

Posted at

地味にハマったのでメモ。

再現

htmlファイルのみで再現できます。
適当に保存して、ブラウザで開くと動作します。

ソースはGitGistにもアップしています。
https://gist.github.com/kai-kou/9b5b613918e107ca23682982c75d9467

index.html
<html>
  <body>
    <div id="app">
      <custom-component
        :msg='msg'
        v-on:hello-hoge="msg = 'OK!!!'"
        v-on:helloHoge="msg = 'OK???'"
      />
    </div>

    <script type="text/x-template" id="custom-component">
      <div>
        <span>{{msg}}</span>
        <button v-on:click="$emit('hello-hoge')">これはOK</button>
        <button v-on:click="$emit('helloHoge')">これはだめ</button>
      </div>
    </script>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script>
      Vue.component("customComponent", {
        props: ["msg"],
        template: "#custom-component",
      })
    </script>

    <script>
      new Vue({
        el: "#app",
        data: {
          msg: 'hoge'
        },
      })
    </script>
  </body>
</html>

helloHoge のボタンをクリックするとコンソールログに警告が出力されます。
開発環境ではこれが出力されず、少々ハマりました。。。

vue.js:603 [Vue tip]: Event "hellohoge" is emitted in component but the handler is registered for "helloHoge". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "hello-hoge" instead of "helloHoge".

Google翻訳

vue.js:603 [Vue tip]:イベント "hellohoge"がコンポーネントで生成されましたが、ハンドラーが "helloHoge"に登録されました。 HTML属性は大文字と小文字を区別しないため、DOM内のテンプレートを使用する場合はv-onを使用してcamelCaseイベントをリスンすることはできません。 おそらく、 "helloHoge"ではなく "hello-hoge"を使用するべきです。

まとめ

複数言語で開発していると、もうどれでどう実装したら良いのかわからなくなってきます。

参考

camelCased custom event name is not working · Issue #4044 · vuejs/vue
https://github.com/vuejs/vue/issues/4044

VueのCDN版を使おう - やわらかVue.js
https://scrapbox.io/vue-yawaraka/Vue%E3%81%AECDN%E7%89%88%E3%82%92%E4%BD%BF%E3%81%8A%E3%81%86

コンポーネントの基本 — Vue.js
https://jp.vuejs.org/v2/guide/components.html

Vue.js の単一ファイルコンポーネント化をHTMLファイルで行う方法 | WriteIfElse
https://blog.bulkus.net/post/vue-htmlfile-components/

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