yyx990803 / vue-hooks

Experimental React hooks implementation in Vue

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Update documentation and examples to use `function` instead of `lambda`

Flamenco opened this issue · comments

I know it is a bit more verbose, but the lambdas do not allow the hook to access the component using this. You cannot capture the instance in a closure outside of the the lambda either, because the component has not been instantiated when the hooks are loaded.

const Foo = withHooks(h => {
  // `this` is not defined so the lambda does not capture it. 
  const double = useComputed(()=>return data.count * 2 )
}
const Foo = withHooks(h => {
  // The computed function will be called with `this` set to the component because lambda is not used.
  const double = useComputed( function() { return data.count * 2 } )
}

@yyx990803 I have to say this is similar to another issue I see this all the time:

data:()=>({foo:'bar'})

When IMHO is should always be:

data(){ return {foo:'bar'} }

The reason I say always is that you do not have access to props, $route, $store, etc if you use the lambda notation, so it really is a best practice to have your Vue code always ready to access this as a valid component instance.

I have submitted a pull request updating the documentation and examples.

I don't really agree with this. In my opinion, you should just use functions if you really need to access the context provided by the caller.

We are advised not to use lambdas for other cases such as created(), mounted(), etc. The same should apply here.

If you want to go rogue and use the lambda, that’s your choice, but it should not be the promoted syntax.

It will also eliminate a whole series of bug reports.

Sure, you can't do that in created, mounted, etc, but that's a total different scenario. AFAIK, the docs don't even mention that you have access to the component when using hooks.

If hooks are to replace mixins, they surely must have access to the component. In my experience, I use these hooks in place of all of my mixins, with the benefit of having input parameters and output parameters.

And the this instance is definitely set when the callbacks are invoked. (As long as you use functions and not lambdas...)

Also, I am not sure how this is a totally different scenario:

const Foo = withHooks(h => {
  useMounted(() => {
    console.log('mounted!')
  })
})

Oh, I thought you meant the lifecycle methods in the usual way to declare components (exporting objects).

Yep, that why I only updated examples 2 and 3 (not 1) in the PR because they wrap the existing mixin and component option access points that all are clearly documented to receive a valid this pointer.