LoginSignup
0
0

More than 3 years have passed since last update.

Vue.jsでControl+EnterとCommand+Enterどちらでも送信できるようにする

Posted at

TL;DR

Vue.jsでControl+EnterとCommand+Enter両方で関数を発火させ、
Enterで発火させないベストプラクティス。

WindowsとMacのControlキー

アプリケーションにおいて投稿機能を開発する際、
Enterで改行、Control+Enterで送信を実装したいじゃないですか。

ただ、MacにはControlキーとは別にCommandキーというのがついていて、両方に同じ機能を割り当てたい。
そこで少しハマったのでアンチパターンと共に紹介します。

アンチパターン

keydownをControl, Commandそれぞれについて割り当てる。

<textarea
    v-model="text"
    ...
    @keydown.enter.meta.exact="[function名]"
    @keydown.enter.control.exact="[function名]"
/>

これだとCommand+Enterは発火したがControl+Enterが効かず、Enterで発火してしまう。
同じkeydownがふたつ定義されている時点で気持ちが悪い。

ベストプラクティス

Enterでイベントを発火させ、イベントオブジェクトからそのとき同時に押しているキーによって場合分けする

<textarea
    v-model="text"
    ...
    @keydown.enter.meta.exact="[function名]"
/>

---

[function名](e: any) {
    // ControlキーまたはCommandキーが同時に押されているか
    if (e.ctrlKey || e.metaKey) // 処理
},

まとめ

同じイベントハンドラを複数定義するのはよくない。
KeyCodeは推奨されていないので、ctrlKey, metaKeyのプロパティで処理できてよかった。

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