Home > database >  How to use Vue3 component inside html
How to use Vue3 component inside html

Time:02-06

I managed to use vue2 components inside html files when I was using webpack with html loader. Component was simply placed into html template and everything worked out of the box. Eg. index.html

<section >
    <cover-hero-carousel
        :backgrounds="{{ hero_backgrounds | json_encode }}"
        :delay="2000"
        :duration="3000"
    >
    </cover-hero-carousel>
</section>

I have tried to do the same with Vue3 with Vite, but no success. Is for Vite needed anything special or is simply not possible anymore, to place vue component anywhere into html and would work.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8"/>
    <link rel="icon" type="image/svg xml" href="/vite.svg"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Title</title>
</head>
<body>
<div id="app">
   <cover-hero-carousel
      :backgrounds="{{ hero_backgrounds | json_encode }}"
      :delay="2000"
      :duration="3000"
    >
    </cover-hero-carousel>
</div>
<script type="module" src="src/assets/js/main.js"></script>
</body>
</html>

CodePudding user response:

Placing Vue components "anywhere into html" and them magically working has never been possible.

What gives you this impression is a combination of two factors:

  • Vue templates look very similar to HTML
  • when a Vue app is mounted into an existing HTML element, its contents are used as template for that app.

Technically, there's an alternative to the above: it's also possible to register Vue components as Custom Elements. That use-case might also give you the false impression that Vue components work anywhere. But you'd still need to load Vue upfront, load and declare the web components before any browser could make sense of them.

Overall, using vue components as web components is more technically challenging than using them in a Vue app's template.


Getting back to your example, for it to work, src/assets/js/main.js would need to load Vue and contain code to mount a Vue app into #app. Also, that Vue app would need to have a <cover-hero-carousel /> registered component.


All of the above is still possible in Vue 3, just like in Vue 2. It's the code in main.js that needs some minor tweaking.

  • Related