Search code examples
javascriptvue-componentvuejs3

Define and reuse inline component in Vue3


Is it possible to define a "sub component" inline in Vue3 which can be reused in the same .vue file/component, but without actually defining a new .vue file (i.e. without defining this sub component as a new component).

The use case is that I have a very specific way of formatting <select> options which is used for multiple <select>s within the same component (.vue file), but which will not be used anywhere else (it's also small, so I am inclined to define this options formatting part inline). I don't necessarily want to copy and paste the formatting (and it would be good to keep it within the same .vue file because it's small).

I realise that this is only syntactic sugar which may or may not be relevant in specific cases (I'm also not seeking advice on whether or not this is a good idea). I'm just looking for a way this can be done (if not, that's also an answer ;-))


Solution

  • You can define h() function to create vnodes inside your setup script in vue 3.

    for example:

    <template>
    <MyComponent />
    </template>
    <script setup>
    const MyComponent = h('div', { class: 'bar', innerHTML: 'hello' })
    </script>
    

    vue document will help you completely. document