Home > Enterprise >  Is there a way to create a vue component and add it to the dom like you would an html element?
Is there a way to create a vue component and add it to the dom like you would an html element?

Time:03-23

I have an alert component that I created ... As an example <AlertComponent message="message" />

I have a method in my main App.vue that will accept a new incoming message object and I would like to create an AlertComponent and add it to the DOM when the message comes in. This is because I may have 1 message or 5 messages so I want to create a component dynamically because once the Component has been added it will display itself for 5 seconds and then remove itself from the view.

I'm unclear how to add a component dynamically to the App.vue dynamically My thought would be to have a div in my templet that I can just "addChild" to or something like that.

What's the recommended Vuejs way of doing this? I didn't want to use a v-for on an alert component because every time a new message comes in I would have to manage an array of them and I'm sure I would end up with issues with databinding redrawing a component that I've already shown on screen before it has a chance to destroy itself.

CodePudding user response:

you can try to use v-if, but also you can try to create new app inside yours just by createApp(App).mount("#app");

CodePudding user response:

I'm looking into this for a go-based site. A couple of possibilities:

  1. You can use Petit Vue, which is a small build of Vue 3 that is designed for this. I'd guess your component isn't very large; if so, this might be a good option for you. You just load the Vue code up from a CDN, and you can put your component code right into your page's Javascript. It's pretty simple.

  2. If you want to do something larger, you want to build Vue (I'm using the newest version, which builds with the new Vite build system), and you need to somehow get the CSS and Javascript bundles it creates to get loaded into your pages. I can explain how to do this in more detail if you really want to try it -- I don't think there's a good tutorial around to point you to.

  3. If you use one of the systems listed here, you can use your platform to do the magic you need to do for (2). I think that Ruby on Rails, Wordpress, Drupal and a few other popular platforms have this.

  • Related