1

I am trying to add specific components to a DOM element whenever the user clicks an button. My code to display the components inside the dom:

<component v-for="(component, index) in components" :key="index" :is="component"></component>

I am using Vue3 with composition.

const components = reactive([]);
components[0] = 'TemplateText';
components[1] = 'TemplateText';

What I would expect is that this component will be loaded two times inside my DOM now. When I check my source code, the component is there two times i.e:

<templatetext data-v-997532dc=""></templatetext>
<templatetext data-v-947231dc=""></templatetext>

but it does not display anything eventhough the components do have tekst in them.

Can anyone tell me what might be wrong? and what would be working method to archieve what I want to do?

1 Answer 1

1

Your components should be registered globally or locally in components option, and the reactive should take an object as parameter or you should use ref instead :

components:{
TemplateText
},
setup(props){
const state= reactive({components:[]});
state.components[0] = 'TemplateText';
state.components[1] = 'TemplateText';

return {state}
}

template :

<component v-for="(component, index) in state.components" :key="index" :is="component"></component>

if you want to just render your components multiple times just loop through a number without using a reactive stuff :

<TemplateText v-for="index in 2" :key="index"/>
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah obviously, so stupid I didnt think about that. It is working fine now, thanks so much! adding them to the "components" did the job ;)

Your Answer

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