Skip to main content

Use Angular Custom Element in Vue.js

2 min read

Older Article

This article was published 8 years ago. Some information may be outdated or no longer applicable.

In a previous article, we looked at Custom Elements with Angular. Now let’s take one of those custom elements and drop it into a supposedly competing framework: Vue.js.

Setup the project

First, install the Vue.js CLI: npm i -g @vue/cli.

Then spin up a new project: vue create custom-element (select the defaults).

Create the application

The CLI generates a shell application with some components already in place. For this demo, we’ll only touch App.vue. Update it to look like this:

<template>
  <div id="app">
    <app-greeter name="John"></app-greeter>
  </div>
</template>

<script>
  export default {
    name: 'app',
  };
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
</style>

Notice the custom element sitting right inside the Vue template.

The last step: grab the JavaScript file generated in the previous article and copy it into the public folder (that’s where Vue.js keeps its index.html file).

The final index.html should look like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title>custom-element</title>
    <script src="app-greeter.js"></script>
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but custom-element doesn't work properly without JavaScript
        enabled. Please enable it to continue.</strong
      >
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

Note the app-greeter.js script tag in the head.

Running the app

Run npm run serve and the custom element should appear in the browser.

Conclusion

We’ve taken a custom element built in Angular and plugged it straight into a Vue.js project. That’s solid interoperability between two popular frameworks. Custom elements are just the starting point for this kind of cross-framework reuse, and I expect we’ll see a lot more of it going forward.