Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

vuejs3 - Vue3 add component to dom dynamically

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?

question from:https://stackoverflow.com/questions/65853312/vue3-add-component-to-dom-dynamically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...