Search code examples
vue.jsvue-componentvuejs3

How do I create reusable template parts in Vue.js?


I have a component with a few blocks that repeat throughout the template. These blocks may have a conditional or two and might call some methods in event handlers, but mostly they're pretty simple.

It is really not worth creating an entire, separate component for a few elements, plus passing around data and methods isn't exactly trivial, making the component more difficult to maintain. So these blocks won't be used in any other components.

I really need to be able to define a "subcomponent" or "template" inside this component for these blocks. I don't know if this is possible yet. Has anyone figured out a clean solution for this?


Solution

  • Components can be defined as render functions, and this is especially easy with JSX:

    const ComponentA = props => (
      <div>
        <label>{props.label} <input type="text" /></label>
      </div>
    )
    

    You could declare multiple subcomponents as render functions (or full component definition objects if needed) in the same file, and reuse them in the component's template. Vue 3's <script setup> block also helps to make this more concise:

    <script lang="jsx" setup>
    const SubComponentA = (props) => (
        <div>
          <label>{props.label}</label>
          <input type="number" />
        </div>
    )
    const SubComponentB = (props) => (
        <div>
          <label>{props.label}</label>
          <textarea />
        </div>
    )
    </script>
    
    <template>
      <SubComponentA label="Label 1" />
      <SubComponentB label="Label 2" />
      <SubComponentA label="Label 3" />
      <SubComponentB label="Label 4" />
    </template>
    

    demo