Stephan-v
Stephan-v

Reputation: 20309

Vue.js named javascript hooks

I am trying to hook up Vue.js with velocity.js. The guide gives an example but does not use a named transition. Currently my transition looks like this:

<transition name="collapse">

https://v2.vuejs.org/v2/guide/transitions.html#JavaScript-Hooks

The example given from the Vue.js documentation sets up a transition element like so:

<transition
  v-on:before-enter="beforeEnter"
  v-on:enter="enter"
  v-on:after-enter="afterEnter"
  v-on:enter-cancelled="enterCancelled"
  v-on:before-leave="beforeLeave"
  v-on:leave="leave"
  v-on:after-leave="afterLeave"
  v-on:leave-cancelled="leaveCancelled"
>

Is there not a way to do this automatically, without having to set all of this up beforehand? The second step of course would be simply having a named animation without having to set all of this up.

Preferably the methods in my Vue.js component would like something like this:

collapseEnter, collapseEnterCancelled, etc.

But this does not seem to work. Do I really have to set up all the directives or is there an easier way?

Upvotes: 1

Views: 213

Answers (2)

CodinCat
CodinCat

Reputation: 15914

You need to. But it is possible to bind those hook functions automatically by creating an abstract component which will wrap the <transition>.

This is hacky but should work.

First we register a component called autoTransition:

Vue.component('autoTransition', {
  props: ['name', 'vm'],
  functional: true,
  abstract: true,
  render (h, ctx) {
    return h('transition', {
      name: ctx.props.name,
      on: {
        'before-enter': ctx.props.vm.beforeEnter,
        'enter': ctx.props.vm.enter,
        // ... other hooks
      }
    }, ctx.children)
  }
})

And you use it like a normal transition, but instead of passing all the hooks, you can now simply pass the entire vm (can be referenced by $root) and the name in case you need:

<auto-transition name="myTransition" :vm="$root">
  <h1 v-show="someBool">hello</h1>
</auto-transition>

Upvotes: 2

Egor Stambakio
Egor Stambakio

Reputation: 18146

AFAIK the name is used only when you are applying CSS classes to transition. It has nothing to do with javascript hooks. So yes, you need to define all hooks explicitly.

Upvotes: 1

Related Questions