SoFunction
Updated on 2025-04-07

N ways to write Vue3 multi-components

Vue itself and its surrounding ecology have hardly disappointed me in designing syntax sugar, including Vue Vine, which was officially unveiled at the VueConf 2024 Shenzhen event.

Its appearance has aroused my curiosity about how Vue3 components are written, and which approaches "best practices"?

So what interesting tool is Vue Vine? And what other tools are similar to this tool? What are their corresponding scenarios? How to choose?

Let me tell you one by one:

SFC single file component

When we write code, we often have duplicate code, such as:

<template>
  <dialog v-if="showInDialog">
    <!-- Code snippet -->
  </dialog>
  <div v-else>
    <!-- Code snippet -->
  </div>
</template>

If we don't want to "Code snippet"What should I do if I write this part repeatedly twice?

At this time, we often take out this code snippet and put it in a newly created one..vueIn subcomponents:

<!-- Parent component -->
<template>
  <dialog v-if="showInDialog">
    <Content />
  </dialog>
  <div v-else>
    <Content />
  </div>
</template>

<!-- Subcomponents  -->
<template>
  <!-- Code snippet -->
</template>

This itself is a componentized development method that Vue officially defaults to, that is, SFC single-file components.

However, in some cases, we may not want to split this part of the "code snippet" into separate single files. For example, when the "code snippet" is very simple, or when the parent component does not have much code...

And the series of tedious operations brought about by forced splitting are sometimes quite annoying. At this time, we have to find some solutions to solve this situation where a single file component cannot solve it.

Multi-template solution

The multi-template solution emphasizes theA single file componentExtracting energyReused templatesCode, in other words, extract the public HTML generation.

createReusableTemplate

VueUseIt is a tool library that provides a lot of practical Vue3 composables, which provides a reusable template.createReusableTemplateMethod, the document link is/core/createReusableTemplate

How to use is very simple:

<script setup>
import { createReusableTemplate } from '@vueuse/core'

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()
</script>

<template>
  <DefineTemplate>
    <!-- Code snippet -->
  </DefineTemplate>

  <dialog v-if="showInDialog">
    <ReuseTemplate />
  </dialog>
  <div v-else>
    <ReuseTemplate />
  </div>
</template>

Use importedDefineTemplateComponent registration template (note that the content will not be rendered at this time), and then use itReuseTemplateComponents to render the template you just registered (note that DefineTemplate must be used before ReuseTemplate).

namedTemplate

Vue MacrosLike magic, it allows you to experience more advanced syntactic sugar in Vue3 projects. And it is also a test field for Vue grammar, and many grammars in it have the chance to be included by Vue!

It provides a named templatenamedTemplateFeatures, the document link is/zh-CN/features/

How to use it is as follows:

<script setup>
const showInDialog = ref(false)
</script>

<template name="reusable">
  <!-- Code snippet -->
</template>

<template>
  <template v-if="showInDialog">
    <dialog>
      <template is="reusable" />
    </dialog>
  </template>
  <template v-else>
    <div>
      <template is="reusable" />
    </div>
  </template>
</template>

Multi-component (stateless) scheme

The multi-component (stateless) scheme emphasizes theA fileDefinition inSingle stateful component + Multiple stateless components

JSX

JSX is the most common solution in multi-component practice, dominating the "multi-component (stateless) solution". There are many ways to write in JSX solutions, involving the knowledge of stateful "components" and stateless "function components".

I'll choose three common solutions here:defineComponent renderdefineRendersetupSFC, other writing styles are not mainstream, so we won’t mention them here.

defineComponent render

This is the most unpretentious way to use JSX in Vue3! Belongs to Vue3 + JSXWhere the dream begins

import { defineComponent, ref } from "vue"

export default defineComponent({
  setup() {
    // Use ref to create a responsive variable to control the display status    const showInDialog = ref(false)
    // Declare a stateless function component Content for rendering code snippets    function Content() {
      return <div>Code snippet</div>
    }
    // Return the render function    return () => (
      <div>
        { ? (
          <dialog>
            <Content />
          </dialog>
        ) : (
          <div>
            <Content />
          </div>
        )}
      </div>
    )
  }
})

defineComponentMethods are used to define components, insetupInside the method, we can use "function components" to define some "stateless components" that need to be reused, and finally return the render function directly.

Essentially, it isdefineComponent + render + stateless function component + JSX"Combined use

defineRender

And defineRender can be regarded asdefineComponent renderIt's also an upgraded versionVue MacrosMethod provided.

usedefineRenderCan be directly in<script setup>Define the rendering function in:

&lt;script setup lang="jsx"&gt;
// Use ref to create a responsive variable to control the display statusconst showInDialog = ref(false)
// Declare a stateless function component Content for rendering code snippetsfunction Content() {
  return &lt;div&gt;Code snippet&lt;/div&gt;
}

defineRender(
  &lt;div&gt;
    { ? (
      &lt;dialog&gt;
        &lt;Content /&gt;
      &lt;/dialog&gt;
    ) : (
      &lt;div&gt;
        &lt;Content /&gt;
      &lt;/div&gt;
    )}
  &lt;/div&gt;
)
&lt;/script&gt;

Although this method has been said goodbyedefineComponentandOptions APIMake the code lighter, but.vueWritten in the middlejsxStill not elegant enough.

So there is an upgraded version about itsetupSFC

setupSFC

setupSFC is one of my favorite solutions for writing JSX components in Vue3 (it is stillVue Macrosprovided method).

When we develop, we need to define the suffix as. / .File:

// Use ref to create a responsive variable to control the display statusconst showInDialog = ref(false)
// Declare a stateless function component Content for rendering code snippetsfunction Content() {
  return &lt;div&gt;Code snippet&lt;/div&gt;
}

export default () =&gt; (
  &lt;div&gt;
    { ? (
      &lt;dialog&gt;
        &lt;Content /&gt;
      &lt;/dialog&gt;
    ) : (
      &lt;div&gt;
        &lt;Content /&gt;
      &lt;/div&gt;
    )}
  &lt;/div&gt;
)

Say goodbyedefineComponentandOptions API,WillsetupandjsxPerfect fusion.

Multi-component (stateful) scheme

The multi-component (stateful) scheme emphasizes theA fileDefinition inMultiple stateful components

JSX

That’s right, after JSX dominated the “multi-component (stateless) scheme”, it is also active in the “multi-component (stateless) scheme”!

defineComponent render

In fact, we have defined the "defineComponent render" mentioned above several times, which is the plan.

import { defineComponent, ref } from "vue"

// Subcomponentsconst Content = defineComponent({
  setup() {
    return () =&gt; &lt;div&gt;Code snippet&lt;/div&gt;
  }
})

// Parent componentconst App = defineComponent({
  setup() {
    const showInDialog = ref(false)

    return () =&gt; (
      &lt;div&gt;
        { ? (
          &lt;dialog&gt;
            &lt;Content /&gt;
          &lt;/dialog&gt;
        ) : (
          &lt;div&gt;
            &lt;Content /&gt;
          &lt;/div&gt;
        )}
      &lt;/div&gt;
    )
  }
})

export default App

Stacking in a filedefineComponentThat's right, this form is similar to that in React"Class Component"

setupComponent

now that"Class Component"Yes, then is there"State Function Components"Woolen cloth?

thenVue MacrosIt also provides a very cool syntax setupComponent that can be used in.jsxThere are multiple "stateful function components" written in the file, which is my favorite solution to write JSX components in Vue3.

// Subcomponentsconst Content = defineSetupComponent(() =&gt; {
  return &lt;div&gt;Code snippet&lt;/div&gt;
})

// Parent componentconst App = defineSetupComponent(() =&gt; {
  const showInDialog = ref(false)

  return (
    &lt;div&gt;
      { ? (
        &lt;dialog&gt;
          &lt;Content /&gt;
        &lt;/dialog&gt;
      ) : (
        &lt;div&gt;
          &lt;Content /&gt;
        &lt;/div&gt;
      )}
    &lt;/div&gt;
  )
})

export default App

Vue Vine

Have you found that all the multi-component solutions in the article so far are based on JSX. Is there any oneUse templates and support multiple componentsWhat about the plan?

Then we have to talk about Vue Vine.

It is worth noting that Vine only supports itVue3 + Vite + TS, then we build a.document:

// Subcomponentsfunction Content() {
  return vine`&lt;div&gt;Code snippet&lt;/div&gt;`
}

// Parent componentfunction App() {
  const showInDialog = ref(false)

  return vine`
    &lt;div&gt;
      &lt;template v-if="showInDialog"&gt;
        &lt;dialog&gt;
          &lt;Content /&gt;
        &lt;/dialog&gt;
      &lt;/template&gt;
      &lt;template v-else&gt;
        &lt;div&gt;
          &lt;Content /&gt;
        &lt;/div&gt;
      &lt;/template&gt;
    &lt;/div&gt;
  `
}

export default App

A function is a component, and thenvineTagged template string declares component templates.

This writing method is just mentionedsetupComponentVery similar, all belong"State Function Components", but the difference is that one returns JSX and the other returns template. The advantage of templates is that Vue has compile-time optimizations for it.

Summarize

  • In most cases, the first choice is stillSFC single file componentJust plan
  • For template reuse, I prefer the one provided by Vue MacrosnamedTemplateHowever, given the current stability, it is recommended to use the provided by VueUsecreateReusableTemplateplan
  • For multi-component scenarios, it is recommended that you choose JSX solutions as the first choice.defineComponent renderplan. Developers who like to try it out can boldly try it out by Vue MacrossetupComponentOr chooseVue Vine

End

The above is the detailed content of N multiple-component writing methods of Vue3. For more information about the multi-component writing methods of Vue3, please pay attention to my other related articles!