composition-api: Refs are undefined in setup() outside of lifecycle method

As a follow-up to https://github.com/liximomo/vue-function-api/issues/10#issue-460033875, the refs are now injected, but they can only be accessed inside of a lifecycle method. I don’t believe this is the desired usage.

For example, I have a custom hook that binds and removes an event listener to the DOM node passed into it as a parameter. Because my custom hook cannot be called inside of a lifecycle method (because it has lifecycle methods inside of it), I can only call my custom hook at the first level of setup(). I like this functionality, and the errors were clear.

console.log("outside:");
console.log(context.refs.elementKeypress); // undefined

onMounted(() => {
  console.log("inside:");
  console.log(context.refs.elementKeypress); // <div data-v-763db97b="" class="element-keypress-demo">Ref</div>
});

// hook fails to bind event listener to 'undefined'
useElementKeypress("u", context.refs.elementKeypress, () => {
  console.log("clicked!");
});

See my CodeSandbox example

My problem is that the ref is undefined when passing it into the custom hook.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 20 (8 by maintainers)

Most upvoted comments

@liximomo I don’t agree. That negates the flexibility of the custom hook. In your example the ref cannot be specified at runtime - it is “prenamed”.

If this is the case, I think the RFC example code above should be altered because refs.foo in the onClick method would NOT be defined

The ref.foo will exist because if the onClick is called the component has already been mounted. Am I right?

I appreciate you talking with me about this, but I don’t think we’re on the same page. Perhaps I’m not communicating this clearly.

I did not mean the actual context. I just meant that the refs are undefined and they are part of context.

Your latest example still is not allowing the developer to declare which ref should be used. It is hard-coded to use the ‘elementKeypress’ ref.

@yyx990803 What do you think about this composition pattern and issue? I believe that refs (and other context) should be usable at the first level of setup(), whereas currently they are ‘undefined’. The two options I see would be to either keep the existing API of defining refs in the markup and utilizing it via context, OR to define refs via another new API, like React does with useRef().