Use Angular Custom Element in Vue.js

This post is 4 years old. (Or older!) Code samples may not work, screenshots may be missing and links could be broken. Although some of the content may be relevant please take it with a pinch of salt.

In a previous article, we discussed Custom Elements with Angular. In this article, we'll now see how to use such custom elements outside Angular and in a supposedly competing framework, Vue.js.

Setup the project

To start a Vue.js application, first, let's go ahead and install the Vue.js CLI: npm i -g @vue/cli.

Once this is done, we can create a new project: vue create custom-element (select the defaults).

Create the application

The CLI creates the shell of the application with some components already in place. For demonstration purposes, we'll only use the App.vue so let's go ahead and update it, so it looks 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 how we are using our custom element inside the Vue template.

The last thing we need to do is to grab the JavaScript file generated in the previous article and copy it to the public folder (this is the folder where Vue.js has it's index.thml file.)

The final index.html file 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>

Notice the inclusion of the app-greeter.js file in there.

Running the app

Now, run the app with npm run serve, and we should see our custom element in the browser.

Conclusion

In this article, we saw how to add a custom element created in an Angular application to a Vue.js project. This enables excellent interoperability between these two, popular frameworks. Going forward, I expect to see more such interoperability between the various frameworks, and custom elements are just the beginning of an exciting journey.