LoginSignup
30
20

More than 5 years have passed since last update.

[Vue.js]祖先のイベントを孫から叩くには

Last updated at Posted at 2018-06-05

やりたかったこと

image.png

こんな感じで孫から祖先の関数を叩きたかった。

結論から先に

001.png
こんな感じで階層ごとに親へ$emitしてやる必要があるみたい。
あくまでも親-子の関係しか存在し得ないので、祖先に渡す場合は一旦親を経由する必要がある。

Code

See the Pen Vue - grandchild-emit by tosite (@tosite) on CodePen.

試してみたこと

(実際のコードとは違いますが、やらんとすることは伝わるかと思います。)

<parent @parent-method="parentMethod">
  <child @parent-method="parentMethod">
    <grand-child @parent-method="parentMethod">
    </grand-child>
  </child>
</parent>

<parent @parent-method="parentMethod">
  <child @parent-method="$parent.parentMethod">
    <grand-child @parent-method="$parent.parentMethod">
    </grand-child>
  </child>
</parent>

こんなことするなら...

Event Bus機能を利用する方がいいのでは。
あるいは Vuex で状態管理するべきか。
Vue、便利なんだけど難しい。

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