radix-vue / shadcn-vue

Vue port of shadcn-ui
https://www.shadcn-vue.com/
MIT License
3.53k stars 204 forks source link

[Bug]: There's no way to manually focus the textarea #564

Closed jd-solanki closed 1 month ago

jd-solanki commented 1 month ago

Reproduction

https://stackblitz.com/edit/t6hymg?file=src%2FApp.vue

Describe the bug

Hi 👋🏻

I want to manually focus textarea when espace key is pressed. However, When I use template ref it doesn't give textarea element 🤷🏻‍♂️

System Info

System:
    OS: macOS 14.4.1
    CPU: (8) arm64 Apple M1
    Memory: 83.38 MB / 8.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.1 - ~/.nvm/versions/node/v20.11.1/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v20.11.1/bin/yarn
    npm: 10.2.4 - ~/.nvm/versions/node/v20.11.1/bin/npm
    pnpm: 8.6.12 - ~/Library/pnpm/pnpm
    bun: 1.0.29 - ~/.bun/bin/bun
  Browsers:
    Brave Browser: 118.1.59.117
    Chrome: 124.0.6367.210
    Safari: 17.4.1
  npmPackages:
    @vueuse/core: ^10.9.0 => 10.9.0 
    nuxt: ^3.11.2 => 3.11.2 
    radix-vue: ^1.7.4 => 1.7.4 
    shadcn-nuxt: ^0.10.4 => 0.10.4 
    vue: ^3.4.27 => 3.4.27

Contributes

sadeghbarati commented 1 month ago

Vue still not support forwardRef.

You can do something like

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Textarea } from '@/components/ui/textarea';
import { unrefElement } from '@vueuse/core'

const refTextarea = ref();

onMounted(() => {
  refTextarea.value.$el.focus()
  // or
  unrefElement(refTextarea).focus()
});
</script>

<template>
  <Textarea ref="refTextarea" placeholder="Type your message here." />
</template>

Related resources

jd-solanki commented 1 month ago

Thanks. I was aware of this but I didn't tried this because my console log had empty ref value, Check below image: image

I think when you use ref on vue component it doesn't give empty ref like above image it logs the component instance and we can inspect the underlying element $el: image

I've updated the reproduction example I guess

Anyways, It indeed solves my query hence closing the issue, Thanks 😇