5

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?

1

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

What does the scope look like for these? Does it only operate with what's passed to it like a normal component or does it have access to the parent component context?
In <script setup>, the subcomponents can have access to the parent component context (demo).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.