Defining Vue 3 Application Scope
The user is looking to build a Vue 3 application that incorporates Web Components and TypeScript decorators. I need to clarify the request to ensure I'm on the right track—are they asking for full app scaffolding? It sounds like they want a complete example structure, possibly using Vite alongside Vue 3, TypeScript, and decorators. This could involve defining components as Web Components with Lit or customElements, as well as showing how TypeScript decorators can be utilized within Vue code.Evaluating TypeScript Decorators for Vue 3
As of TypeScript 5.x, there's a new standard for decorators, but many still use the older "experimental" version. In Vue 3, class-style components with decorators aren't the main focus since the emphasis is on the Composition API. Still, libraries like vue-class-component 8 support class components with decorators. I need to decide whether to demonstrate those or explore TS decorators for other use cases, like mobx-state-tree. However, the user likely wants to see integration examples.Planning the App Structure
I should create a small app that demonstrates defining Web Components using TypeScript decorators, like a @CustomElement('my-counter') decorator for registration. This Vue 3 app will be built with TypeScript, allowing for optional decorators. I'll show how Vue components utilize these Web Components and cover interop details: handling attributes vs props, events, and v-model. Additionally, I could wrap a Web Component as a Vue component using defineCustomElement or defineComponent. Using Vite as the bundler for this setup will make things smoother, and I’ll provide a clear, step-by-step guide.Preparing Project Details
I plan to provide key components like project setup commands, a tsconfig snippet, a main.ts file, a decorator helper file, and the Web Component file. I won't go into detail about installing Node, as I'll focus on the developer audience. I also need to ensure that any TypeScript decorators I use follow the realistic syntax of TS 5, weighing the options between new standard decorators and legacy versions. While many bundlers still support "experimentalDecorators," it's often simpler to demonstrate with "experimentalDecorators: true," despite potential warnings in TS 5.Detailing Decorator Implementation
I'm deciding to focus on experimental decorators and will outline how to enable them. I’ll provide a CustomElement decorator function for defining Web Components, while optionally skipping a property decorator for brevity. Since the user wants to integrate Web Components with TypeScript decorators, I will create a simple Web Component with this decorator and provide a Vue 3 wrapper. I'll include setup commands with Vite and discuss how to configure TypeScript options for decorators, ensuring the provided code will function correctly under typical configurations.Providing Project Structure
I’m clarifying that I’ll detail a Vue 3 project using TypeScript decorators for Web Components. First, I need to confirm the configuration for using decorators in TypeScript 5, balancing between experimental and standard decorators. I’ll introduce a high-level overview of the setup, covering how to create a project with Vite and specifying commands.
Then, I’ll outline each step, including creating the CustomElement decorator, making the my-counter Web Component, and integrating it into a Vue component while managing event bindings. Finally, I’ll distribute concise code snippets to provide structure without overwhelming detail.Creating the MyCounter Class
I’m working on the MyCounter class as a Web Component using TypeScript decorators. The class will include functionalities for incrementing and decrementing a count, with methods to render the component and dispatch events. I’ll use the CustomElement decorator to define the custom tag.
To further showcase decorators, I can add an @Emit decorator to handle automatic event dispatching when the count changes. I’ll also focus on keeping the code succinct while ensuring clarity in each explanation and piece of code provided. Below is a small but complete example of a Vue 3 + TypeScript app that:
- Uses Web Components (Custom Elements).
- Uses TypeScript decorators to define and wire up those Web Components.
- Integrates them into Vue components.
I’ll assume a Vite-based Vue 3 + TS setup.
1. Create the Vue 3 + TypeScript project
npm create vite@latest vue-wc-decorators -- --template vue-ts
cd vue-wc-decorators
npm install
2. Enable decorators in TypeScript
In tsconfig.json (or tsconfig.app.json if you have one), ensure these options exist inside "compilerOptions":
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
// For legacy-style decorators (what this example uses)
"experimentalDecorators": true,
"useDefineForClassFields": true,
"lib": ["ESNext", "DOM"]
}
}
Note: This example uses the widely supported “legacy” decorator semantics (experimentalDecorators: true). If you use TypeScript 5+ with standard decorators, the decorator function signatures change slightly, but the usage (@Decorator) in code is the same.
3. Add decorator utilities for Web Components
Create src/web-components/decorators.ts:
// src/web-components/decorators.ts
// Class decorator for defining a custom element.
type CustomElementClass = { new (...args: any[]): HTMLElement };
export function CustomElement(tagName: string) {
return function <T extends CustomElementClass>(constructor: T) {
if (!customElements.get(tagName)) {
customElements.define(tagName, constructor);
}
};
}
// Method decorator to automatically emit a CustomEvent with the method’s return value
// as `detail`.
export function Emit(eventName: string) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
const result = original.apply(this, args);
this.dispatchEvent(
new CustomEvent(eventName, {
detail: result,
bubbles: true,
composed: true,
})
);
return result;
};
return descriptor;
};
}
4. Implement a Web Component using TypeScript decorators
Create src/web-components/MyCounter.ts:
// src/web-components/MyCounter.ts
import { CustomElement, Emit } from './decorators';
@CustomElement('my-counter')
export class MyCounter extends HTMLElement {
private _count = 0;
private shadow: ShadowRoot;
get count(): number {
return this._count;
}
set count(value: number) {
const numeric = Number(value);
if (!Number.isNaN(numeric) && numeric !== this._count) {
this._count = numeric;
this.render();
}
}
constructor() {
super();
this.shadow = this.attachShadow({ mode: 'open' });
}
static get observedAttributes() {
return ['count'];
}
attributeChangedCallback(name: string, _oldVal: string | null, newVal: string | null) {
if (name === 'count' && newVal !== null) {
this.count = Number(newVal);
}
}
connectedCallback() {
// Initialize from attribute if present
const initialAttr = this.getAttribute('count');
if (initialAttr !== null) {
this.count = Number(initialAttr);
}
this.render();
}
private render() {
this.shadow.innerHTML = `
<style>
:host {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
font-family: system-ui, sans-serif;
}
button {
cursor: pointer;
}
</style>
<button id="dec">-</button>
<span>${this.count}</span>
<button id="inc">+</button>
`;
this.shadow.getElementById('inc')?.addEventListener('click', () => {
this.increment();
});
this.shadow.getElementById('dec')?.addEventListener('click', () => {
this.decrement();
});
}
// These methods are decorated to emit CustomEvents automatically.
@Emit('counter-change')
private increment(): number {
this.count++;
this.render();
return this.count; // becomes event.detail
}
@Emit('counter-change')
private decrement(): number {
this.count--;
this.render();
return this.count; // becomes event.detail
}
}
What this gives you:
@CustomElement('my-counter') automatically calls customElements.define('my-counter', MyCounter).
@Emit('counter-change') wraps increment/decrement to dispatch CustomEvent<number> named "counter-change" whose detail is the new count.
- The component:
- Accepts a
count attribute or property.
- Renders buttons in Shadow DOM.
- Notifies changes via
counter-change events.
5. Register Web Components in the Vue app
Just importing the file is enough to run the decorators and register the element.
Edit src/main.ts:
// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
// Register Web Components (side-effect import)
import './web-components/MyCounter';
createApp(App).mount('#app');
6. Use the Web Component inside a Vue 3 component
6.1 App root
src/App.vue:
<template>
<div class="app">
<h1>Vue 3 + Web Components + TypeScript Decorators</h1>
<WcHost />
</div>
</template>
<script setup lang="ts">
import WcHost from './components/WcHost.vue';
</script>
<style scoped>
.app {
font-family: system-ui, sans-serif;
padding: 2rem;
}
</style>
6.2 Host component that interacts with the Web Component
Create src/components/WcHost.vue:
<template>
<section>
<h2>Counter implemented as a Web Component</h2>
<p>Current count (tracked in Vue): {{ currentCount }}</p>
<!--
Binding:
- :count="currentCount" sets a DOM property on <my-counter>.
- @counter-change listens for CustomEvent<number> from the WC.
-->
<my-counter
:count="currentCount"
@counter-change="onCounterChange"
></my-counter>
</section>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const currentCount = ref(0);
function onCounterChange(e: CustomEvent<number>) {
currentCount.value = e.detail;
}
</script>
<style scoped>
section {
border: 1px solid #ddd;
padding: 1rem;
border-radius: 4px;
max-width: 400px;
}
</style>
Notes:
- Vue treats
<my-counter> as a native element (because of the hyphen), so no extra config is needed.
:count="currentCount" sets a property count on the my-counter DOM instance, which our Web Component exposes.
@counter-change attaches a DOM event listener; it receives the CustomEvent<number> from our decorator-enhanced methods.
7. Run the app
npm run dev
Open the browser (usually http://localhost:5173/):
- You’ll see the Vue app.
- The Web Component counter is rendered.
- Clicking +/− in the Web Component updates Vue state via the
counter-change event.
8. Optional: wrap the Web Component in a typed Vue component
If you want a fully typed interface around the Web Component, add a thin Vue wrapper:
<!-- src/components/MyCounterWrapper.vue -->
<template>
<my-counter
:count="count"
@counter-change="$emit('update:count', ($event as CustomEvent<number>).detail)"
></my-counter>
</template>
<script setup lang="ts">
const props = defineProps<{
count: number;
}>();
const emit = defineEmits<{
'update:count': [value: number];
}>();
</script>
Then you can use it with v-model:count:
<MyCounterWrapper v-model:count="currentCount" />
This structure gives you:
- A Vue 3 + TS app.
- Web Components implemented in TypeScript with decorators (
@CustomElement, @Emit).
- Clean integration between Vue and those Web Components (props/attributes and custom events).