Exploring Application Architecture
I'm currently focused on the overarching architecture. My thought process started with defining the goal: a Vue 3 app using Web Components and TypeScript decorators. Now, I'm diving deeper into how these elements will interact and fit together, considering the best structure for optimal performance. I'm exploring different architectural patterns to find the most efficient and maintainable solution.
Integrating Advanced Features
I've been concentrating on integrating the Web Components and TypeScript decorators. Now, I'm researching vue-facing-decorator to ensure optimal class component behavior in Vue 3. My focus is now on the Web Component approach, considering how best to integrate it with the Vue app for seamless functionality. I'm aiming for a straightforward, maintainable design.
Developing a Proof-of-Concept
I'm now deep into implementation. I've installed vue-facing-decorator and configured TypeScript for experimental decorators. A "user-card" Web Component is underway; it'll take a name and emit an event. I'm focusing on the Vue configuration now, specifically template.compilerOptions.isCustomElement in vite.config.ts to prevent Vue from trying to interpret my custom element. I'm striving to quickly build the component that brings these elements together.
Updating Component Design
I'm now refining the component implementation. I've reevaluated class components and opted for vue-facing-decorator to avoid potential complications. Focusing on keeping the Web Component straightforward, I'll use attributes for simplicity, and this demo component will have no complex data properties. My project started with a npm create vite@latest command, with TypeScript set up to enable experimental decorators. I'm focusing on crafting the Web Component which will be simple.
Implementing Advanced Integration
I've been working on integrating the custom element and Vue component and have progressed further. The Vite config now includes a specific tag regex to handle simple Web Components. I've built a Vue component (DecoratorView.vue) demonstrating state, methods, and lifecycle hooks and binding to the custom element. This highlights the required usage of vue-facing-decorator. The solution appears runnable, and the steps are clear. I believe that I now have a solid design.
Detailing Integration Steps
I'm now carefully documenting the integration process. I'm ensuring props and events are managed effectively with decorators, highlighting @Prop for demonstration. I'm also confirming naming conventions like simple-card for the custom element. Finally, I'm making sure to include the main.ts snippet to clearly illustrate the Web Component import. I've reevaluated creating a Vue component as a Web Component and will focus instead on consuming an external Web Component, which is a more accurate reflection of "integration."
This guide will walk you through building a Vue 3 application that satisfies two specific requirements:
- Consuming a standard Web Component (Custom Element).
- Using Class-based Components with TypeScript Decorators.
Since Vue 3 natively moved away from Class Components in favor of the Composition API, we will use vue-facing-decorator. This is currently the standard library for using Class Components + Decorators in Vue 3, as the official vue-class-component is in maintenance mode.
Prerequisites
- Node.js and npm installed.
Step 1: Scaffolding the Project
Create a new Vite project with Vue and TypeScript.
npm create vite@latest vue-decorator-wc -- --template vue-ts
cd vue-decorator-wc
npm install
Step 2: Install Dependencies
Install the decorator library.
npm install vue-facing-decorator
Step 3: TypeScript Configuration
To use decorators, you must enable them in your tsconfig.json. Add experimentalDecorators, and ensure emitDecoratorMetadata is set if needed (usually good practice with decorators).
Open tsconfig.app.json (or tsconfig.json) and modify compilerOptions:
{
"compilerOptions": {
// ... existing options ...
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictPropertyInitialization": false
}
}
Step 4: Create a Native Web Component
We will create a Vanilla JS/TS Web Component. This simulates bringing in a third-party design system or a legacy component.
Create a file: src/web-components/user-card.ts
// This is a standard Web Component (no Vue dependencies here)
export class UserCard extends HTMLElement {
static get observedAttributes() {
return ['username', 'role'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.render();
// Add a click listener to dispatch a custom event
this.shadowRoot?.querySelector('button')?.addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('card-selected', {
detail: { username: this.getAttribute('username') },
bubbles: true,
composed: true
}));
});
}
attributeChangedCallback() {
this.render();
}
render() {
const username = this.getAttribute('username') || 'Guest';
const role = this.getAttribute('role') || 'User';
if (this.shadowRoot) {
this.shadowRoot.innerHTML = `
<style>
div {
border: 1px solid #ccc;
padding: 16px;
border-radius: 8px;
font-family: sans-serif;
background-color: #f9f9f9;
max-width: 300px;
margin-bottom: 10px;
}
h3 { margin: 0 0 5px; color: #333; }
p { margin: 0 0 10px; color: #666; font-size: 0.9em;}
button {
background: #42b883;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
border-radius: 4px;
}
</style>
<div>
<h3>${username}</h3>
<p>Role: ${role}</p>
<button>Select User</button>
</div>
`;
}
}
}
// Register the custom element
// Example tag: <user-card>
if (!customElements.get('user-card')) {
customElements.define('user-card', UserCard);
}
Step 5: Configure Vite/Vue to Support Custom Elements
By default, Vue tries to resolve every tag as a Vue component. We need to tell the Vue compiler to ignore our custom <user-card> tag so the browser can handle it.
Open vite.config.ts:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
// Treat any tag starting with "user-" as a custom element
isCustomElement: (tag) => tag.startsWith('user-')
}
}
})
],
})
Step 6: Create a Vue Class Component with Decorators
Now we create a Vue component that uses TypeScript decorators to manage state and props, and renders the Web Component we created earlier.
Create src/components/Dashboard.vue:
<template>
<div class="dashboard">
<h2>Decorator Dashboard</h2>
<div class="controls">
<label>Change Role: </label>
<input v-model="currentRole" placeholder="Enter role" />
</div>
<!--
Using the Web Component.
- :username binds Vue state to the WC attribute.
- @card-selected listens to the DOM event emitted by the WC.
-->
<user-card
:username="adminName"
:role="currentRole"
@card-selected="onUserSelected"
></user-card>
<div v-if="lastSelected" class="log">
Last selected: <strong>{{ lastSelected }}</strong>
</div>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-facing-decorator';
// The @Component decorator defines this class as a Vue component
@Component
export default class Dashboard extends Vue {
// Class properties automatically become Reactive State (data)
adminName: string = 'Alice Loginova';
currentRole: string = 'System Admin';
lastSelected: string | null = null;
// Class methods automatically become Vue methods
onUserSelected(event: CustomEvent) {
console.log('Event received from Web Component:', event.detail);
this.lastSelected = event.detail.username;
// Demonstrate modifying state
this.adminName = this.adminName === 'Alice Loginova' ? 'Bob Smith' : 'Alice Loginova';
}
// Lifecycle hooks are just class methods
mounted() {
console.log('Dashboard Component Mounted via Decorators!');
}
}
</script>
<style scoped>
.dashboard {
border: 2px dashed #42b883;
padding: 20px;
margin-top: 20px;
}
.controls {
margin-bottom: 20px;
}
</style>
Step 7: Integrate into the App
Register the Web Component and mount the Vue component.
Open src/main.ts:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// Import the Web Component definition so it registers with the browser
import './web-components/user-card'
createApp(App).mount('#app')
Open src/App.vue:
<script setup lang="ts">
import Dashboard from './components/Dashboard.vue';
</script>
<template>
<div>
<h1>Vue 3 + Web Components + Decorators</h1>
<Dashboard />
</div>
</template>
Step 8: Run the application
npm run dev
How it works
vue-facing-decorator: Vue 3 uses a setup() function internally. This library takes the Class syntax (class X extends Vue) and the properties inside it and converts them into Proxy-based reactive objects compatible with Vue 3's Composition API.
- Web Component Integration:
- The
vit.config.ts change (isCustomElement) prevents Vue from throwing "Failed to resolve component: user-card" warnings.
- In the template, we bind data using standard Vue syntax (
:username="..."). Vue is smart enough to detect that user-card is a custom element and sets the usage as an HTML Attribute rather than a Vue Prop.
- We listen to events using
@card-selected. Vue attaches a standard event listener to the DOM element.
Additional Decorator Features
If you want to expand the Dashboard.vue, here is how you use Props and Watchers with this library:
import { Component, Vue, Prop, Watch } from 'vue-facing-decorator';
@Component
export default class Dashboard extends Vue {
// Defining a Prop
@Prop({ default: 'Default Title' })
title!: string;
someData = 'test';
// Watching a property
@Watch('someData')
onDataChanged(newValue: string, oldValue: string) {
console.log(`Changed from ${oldValue} to ${newValue}`);
}
}