nuxt-community / composition-api

Composition API hooks for Nuxt 2.
https://composition-api.nuxtjs.org
MIT License
706 stars 101 forks source link

help: dynamic component with `script setup` #592

Closed ewilan-riviere closed 2 years ago

ewilan-riviere commented 2 years ago

📚 What are you trying to do? Please describe.

I want to use <component> to create a dynamic component. When I use Vue 2 syntax, everything works but when I use script setup syntax, I have an error component is not defined.

🔍 What have you tried?

With Vue 2 syntax, it works:

<template>
  <component :is="component">
    <slot />
  </component>
</template>

<script>
export default {
  data() {
    return {
      component: 'button',
    }
  },
}
</script>

With script setup syntax, I have an error:

<template>
  <component :is="component">
    <slot />
  </component>
</template>

<script setup lang="ts">
const component = ref('button')
</script>

ℹī¸ Additional context

image

adr1enbe4udou1n commented 2 years ago

Seems like 'component` is a reserved key word on template setup syntax ? It works with different variable name :

<script setup lang="ts">
import { ref } from '@nuxtjs/composition-api'

const tag = ref('button')
</script>

Note : idk if it's only me, but I was forced to add import { ref } from '@nuxtjs/composition-api'... Note 2 : no need of this ugly import after migrate to the new Nuxt Bridge (beta) ! Discussion : #585 See (pretty heavy) migration guide : https://v3.nuxtjs.org/getting-started/bridge/

ewilan-riviere commented 2 years ago

For auto import like ref, I use https://github.com/antfu/unplugin-auto-import, it's really amazing ;)

It's work perfectly, thanks! I didn't know component is reserved I should have checked ^^' I will migrate soon to Bridge, need to migrate my components to script setup before that :D

adr1enbe4udou1n commented 2 years ago

Very thx @ewilan-riviere, didn't known that this @antfu plugin worked in Nuxt too ! It seems a far cleaner solution than Nuxt Bridge, at least for now 😊