### Install Dependencies and Start Development Server
Source: https://github.com/vuejs/core/blob/main/packages-private/sfc-playground/src/download/template/README.md
Use these commands to install project dependencies and launch the development server with your preferred package manager (npm, yarn, or pnpm).
```sh
npm install
npm run dev
# if using yarn:
yarn
yarn dev
# if using pnpm:
pnpm install
pnpm run dev
```
--------------------------------
### Run SFC Playground Locally in Dev Mode
Source: https://github.com/vuejs/core/blob/main/packages-private/sfc-playground/README.md
Start the SFC Playground in development mode from the repository root. This enables hot-reloading and development features.
```shell
pnpm dev-sfc
```
--------------------------------
### Render Vue application to string using `renderToString` in JavaScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This example demonstrates how to use `renderToString` to server-render a basic Vue application. It imports necessary functions, creates a Vue SSR app, and then asynchronously renders it to an HTML string, which is subsequently logged to the console.
```js
const { createSSRApp } = require('vue')
const { renderToString } = require('@vue/server-renderer')
const app = createSSRApp({
data: () => ({ msg: 'hello' }),
template: `
{{ msg }}
`,
})
;(async () => {
const html = await renderToString(app)
console.log(html)
})()
```
--------------------------------
### Update Vue and Compat Dependencies in package.json
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Modify the `package.json` file to upgrade `vue` to version 3.1, install `@vue/compat` of the same version, and replace `vue-template-compiler` with `@vue/compiler-sfc` for Vue 3 compatibility.
```diff
"dependencies": {
- "vue": "^2.6.12",
+ "vue": "^3.1.0",
+ "@vue/compat": "^3.1.0"
...
},
"devDependencies": {
- "vue-template-compiler": "^2.6.12"
+ "@vue/compiler-sfc": "^3.1.0"
}
```
--------------------------------
### Vue SSR App with Idle Hydration Strategy
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-idle.html
Complete setup for an SSR app using hydrateOnIdle() hydration strategy with an async component. The async component loader uses requestIdleCallback to defer heavy work, and hydration is triggered when the browser is idle.
```javascript
window.isHydrated = false
const { createSSRApp, defineAsyncComponent, h, ref, onMounted, hydrateOnIdle, } = Vue
const Comp = {
setup() {
const count = ref(0)
onMounted(() => {
console.log('hydrated')
window.isHydrated = true
})
return () => h('button', { onClick: () => count.value++ }, count.value)
},
}
const AsyncComp = defineAsyncComponent({
loader: () => new Promise(resolve => {
window.resolveLoader = () => {
setTimeout(() => {
console.log('resolve')
resolve(Comp)
requestIdleCallback(() => {
console.log('busy')
})
}, 10)
}
}),
hydrate: hydrateOnIdle(),
})
createSS RApp({
render: () => h(AsyncComp),
}).mount('#app')
```
--------------------------------
### Render Vue application to custom simple stream using `renderToSimpleStream` in JavaScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This example demonstrates using `renderToSimpleStream` with a custom `SimpleReadable` object. It shows how to implement the `push` method to accumulate rendered chunks and the `destroy` method to handle errors, providing a flexible way to process streamed output.
```js
let res = ''
renderToSimpleStream(
app,
{},
{
push(chunk) {
if (chunk === null) {
// done
console.log(`render complete: ${res}`)
} else {
res += chunk
}
},
destroy(err) {
// error encountered
},
},
)
```
--------------------------------
### Vue App Initialization with Grid Data and Configuration
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/grid.html
Root Vue application setup that mounts the DemoGrid component with sample data. Defines grid columns, initial data rows, and search query state for filtering functionality.
```javascript
Vue.createApp({
components: {
DemoGrid,
},
data: () => ({
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 },
],
}),
}).mount('#demo')
```
--------------------------------
### Initialize Items and Setup Vue App Instance
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/list.html
Creates initial item array and configures Vue application with data, methods for list manipulation (insert, reset, shuffle, remove), and component registration. The app manages item IDs and provides reactive list state management.
```javascript
const getInitialItems = () => [1, 2, 3, 4, 5]
let id = getInitialItems().length + 1
const Item = {
props: ['msg'],
template: `
{{ msg }}
`,
}
Vue.createApp({
components: {
Item,
},
data() {
return {
items: getInitialItems(),
}
},
methods: {
insert() {
const i = Math.round(Math.random() * this.items.length)
this.items.splice(i, 0, id++)
},
reset() {
this.items = getInitialItems()
},
shuffle() {
this.items = _.shuffle(this.items)
},
remove(item) {
const i = this.items.indexOf(item)
if (i > -1) {
this.items.splice(i, 1)
}
},
},
}).mount('#app')
```
--------------------------------
### Return Vue application as Web ReadableStream using `renderToWebStream` in JavaScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This example demonstrates how to use `renderToWebStream` to generate a Web ReadableStream from a Vue application. The stream can then be used to construct a `Response` object in environments that support the Web Streams API, such as service workers or edge functions.
```js
// inside an environment with ReadableStream support
return new Response(renderToWebStream(app))
```
--------------------------------
### Configure Plain Webpack for Vue 3 Compat Mode
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Alias `vue` to `@vue/compat` and enable Vue 2 compatibility mode in the `vue-loader` options within `webpack.config.js` for projects using a plain webpack setup.
```javascript
// webpack.config.js
module.exports = {
resolve: {
alias: {
vue: '@vue/compat',
},
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compilerOptions: {
compatConfig: {
MODE: 2,
},
},
},
},
],
},
}
```
--------------------------------
### Async Component with Deferred Hydration on Interaction
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html
Creates an async component wrapper that defers hydration until user interaction (click or wheel events). Uses defineAsyncComponent with hydrateOnInteraction to optimize performance by deferring expensive hydration work.
```javascript
const AsyncComp = defineAsyncComponent({
loader: () => Promise.resolve(Comp),
hydrate: hydrateOnInteraction(['click', 'wheel']),
})
```
--------------------------------
### SSR App Creation and Mounting with Root Hydration Tracking
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html
Creates a Vue SSR app using createSSRApp, sets up root component onMounted lifecycle to track when root is mounted, renders the async component, and mounts to the #app DOM element. Demonstrates the complete SSR hydration flow.
```javascript
createSSRApp({
setup() {
onMounted(() => {
window.isRootMounted = true
})
return () => h(AsyncComp)
},
}).mount('#app')
```
--------------------------------
### Pipe Vue application to Node.js Writable stream using `pipeToNodeWritable` in JavaScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This example shows how to use `pipeToNodeWritable` to stream the rendered Vue application directly into an existing Node.js writable stream, such as an HTTP response object. This is an efficient alternative to `renderToNodeStream` for Node.js environments.
```js
// inside a Node.js http handler
pipeToNodeWritable(app, {}, res)
```
--------------------------------
### Vue.js Main Application Initialization and State Management
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html
This JavaScript block initializes the main Vue 3 application. It defines an initial `globalStats` array, sets up reactive state using `ref` and `reactive`, and includes methods (`add`, `remove`) to manipulate the `stats` array. The application registers the `Polygraph` component and mounts itself to the `#demo` element, demonstrating dynamic data updates and component interaction.
```javascript
const globalStats = [
{ label: 'A', value: 100 },
{ label: 'B', value: 100 },
{ label: 'C', value: 100 },
{ label: 'D', value: 100 },
{ label: 'E', value: 100 },
{ label: 'F', value: 100 }
];
createApp({
components: {
Polygraph
},
setup() {
const newLabel = ref('');
const stats = reactive(globalStats);
function add(e) {
e.preventDefault();
if (!newLabel.value) return;
stats.push({
label: newLabel.value,
value: 100
});
newLabel.value = '';
}
function remove(stat) {
if (stats.length > 3) {
stats.splice(stats.indexOf(stat), 1);
} else {
alert("Can't delete more!");
}
}
return { newLabel, stats, add, remove };
}
}).mount('#demo');
```
--------------------------------
### Pipe Vue application to Web WritableStream using `pipeToWebWritable` in JavaScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This example shows how to use `pipeToWebWritable` in conjunction with a `TransformStream` to stream a Vue application to a Web WritableStream. This pattern is useful in environments like Cloudflare Workers or Node.js (with explicit import) for creating a streaming HTTP response.
```js
// TransformStream is available in environments such as CloudFlare workers.
// in Node.js, TransformStream needs to be explicitly imported from 'stream/web'
const { readable, writable } = new TransformStream()
pipeToWebWritable(app, {}, writable)
return new Response(readable)
```
--------------------------------
### Stream Vue application to Node.js response using `renderToNodeStream` in JavaScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This example demonstrates piping the output of `renderToNodeStream` directly to a Node.js HTTP response object. This method is suitable for server-side rendering in Node.js environments, providing a streaming response for improved performance.
```js
// inside a Node.js http handler
renderToNodeStream(app).pipe(res)
```
--------------------------------
### Vue App Instance - Polygraph Application Setup
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/svg.html
Root Vue application instance that manages global stats data and provides methods for adding/removing stats. Initializes with six default stats and includes form submission and deletion handlers with validation. Mounts to #demo element.
```javascript
const globalStats = [
{ label: 'A', value: 100 },
{ label: 'B', value: 100 },
{ label: 'C', value: 100 },
{ label: 'D', value: 100 },
{ label: 'E', value: 100 },
{ label: 'F', value: 100 }
]
Vue.createApp({
components: {
Polygraph
},
data: () => ({
newLabel: '',
stats: globalStats
}),
methods: {
add(e) {
e.preventDefault()
if (!this.newLabel) return
this.stats.push({
label: this.newLabel,
value: 100
})
this.newLabel = ''
},
remove(stat) {
if (this.stats.length > 3) {
this.stats.splice(this.stats.indexOf(stat), 1)
} else {
alert("Can't delete more!")
}
}
}
}).mount('#demo')
```
--------------------------------
### Fragment Detection and HTML Injection
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html
Detects if the page is running in fragment mode via URL search parameters and conditionally injects pre-rendered HTML with Vue hydration markers into the app container. This simulates SSR output with fragment syntax.
```javascript
const isFragment = location.search.includes('?fragment')
if (isFragment) {
document.getElementById('app').innerHTML = `onetwo`
}
```
--------------------------------
### CSS Base Styles for Body
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html
Sets default margin to zero for the body element to remove browser default spacing. This is a foundational CSS reset commonly used in web applications.
```css
body { margin: 0; }
```
--------------------------------
### Vue Imports for SSR and Hydration
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html
Destructures essential Vue functions for SSR and hydration: createSSRApp for server-side app creation, defineAsyncComponent for lazy-loaded components, h for render functions, ref for reactivity, lifecycle hooks, and hydrateOnInteraction for deferred hydration.
```javascript
const { createSSRApp, defineAsyncComponent, h, ref, onMounted, hydrateOnInteraction, } = Vue
```
--------------------------------
### Import Vue Composition API and Utilities
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-visible.html
Destructures essential Vue functions from the Vue global object including SSR app creation, async component support, render functions, reactivity, lifecycle hooks, and hydration utilities. These are used throughout the hydration setup.
```javascript
const { createSSRApp, defineAsyncComponent, h, ref, onMounted, hydrateOnVisible, createCommentVNode, } = Vue
```
--------------------------------
### Configure RequireJS for Monaco Editor in Vue.js
Source: https://github.com/vuejs/core/blob/main/packages-private/template-explorer/local.html
Sets up RequireJS configuration to load Monaco Editor from node_modules and initializes the editor. This configuration specifies the path to Monaco Editor's VS module and triggers the init function upon successful module loading. Requires Monaco Editor to be installed as a dependency.
```javascript
require.config({
paths: {
vs: './node_modules/monaco-editor/min/vs'
}
})
require(['vs/editor/editor.main'], init /* injected by build */)
```
--------------------------------
### CSS Styling for Vue.js Polygraph Demo
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html
This CSS block provides styling for the Vue.js polygraph demonstration. It defines basic font styles for the body, visual properties for the SVG `polygon` (fill, opacity), `circle` (stroke), and `text` elements (font, fill). Additionally, it includes styling for `label` elements and positions a `#raw` element, enhancing the visual presentation of the interactive polygraph.
```css
body { font-family: Helvetica Neue, Arial, sans-serif; }
polygon { fill: #42b983; opacity: 0.75; }
circle { fill: transparent; stroke: #999; }
text { font-family: Helvetica Neue, Arial, sans-serif; font-size: 10px; fill: #666; }
label { display: inline-block; margin-left: 10px; width: 20px; }
#raw { position: absolute; top: 0; left: 300px; }
```
--------------------------------
### Vue Component with Reactive Counter and Hydration Tracking
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html
Defines a Vue component with a reactive counter using ref() and onMounted lifecycle hook to track hydration completion. Returns conditional JSX-style rendering: either a button with click handler or a fragment containing spans and button based on isFragment flag.
```javascript
const Comp = {
setup() {
const count = ref(0)
onMounted(() => {
console.log('hydrated')
window.isHydrated = true
})
return () => {
const button = h(
'button',
{ onClick: () => count.value++ },
count.value,
)
if (isFragment) {
return [[h('span', 'one')], button, h('span', 'two')]
} else {
return button
}
}
},
}
```
--------------------------------
### HTML UI Elements for Vue.js Polygraph Demo
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html
This HTML snippet represents additional UI elements that would typically be part of the main application's template, interacting with the `Polygraph` component. It displays the `stat.label` and `stat.value`, provides an input field for adding new stats, and shows the raw `stats` array for debugging or demonstration purposes. These elements demonstrate how user input can modify the reactive `stats` data.
```html
{{stat.label}} {{stat.value}} X
Add a Stat
{{ stats }}
```
--------------------------------
### Vue.js Polygraph Coordinate Conversion Helper Function
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html
This JavaScript helper function, `valueToPoint`, converts a data value and its index within a total set into `x` and `y` coordinates suitable for an SVG radar chart. It calculates the angular position and radial distance based on the input value, returning an object with `x` and `y` properties. This function is crucial for dynamically drawing the polygraph and positioning labels.
```javascript
function valueToPoint(value, index, total) {
var x = 0;
var y = -value * 0.8;
var angle = ((Math.PI * 2) / total) * index;
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var tx = x * cos - y * sin + 100;
var ty = x * sin + y * cos + 100;
return { x: tx, y: ty };
}
```
--------------------------------
### Vue.js Polygraph Chart Component Definition
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html
The `Polygraph` Vue component is the main container for the radar chart visualization. It accepts a `stats` array prop, which contains the data points to be plotted. Its `setup` function includes a computed property `points` that transforms the `stats` data into a string of SVG polygon points using the `valueToPoint` helper, dynamically drawing the chart. It also registers the `AxisLabel` component for rendering axis labels.
```javascript
const Polygraph = {
props: ['stats'],
template: '#polygraph-template',
setup(props) {
return {
points: computed(() => {
const total = props.stats.length;
return props.stats
.map((stat, i) => {
const point = valueToPoint(stat.value, i, total);
return point.x + ',' + point.y;
})
.join(' ');
})
};
},
components: {
AxisLabel
}
};
```
--------------------------------
### Updated createApp API Usage
Source: https://github.com/vuejs/core/blob/main/changelogs/CHANGELOG-3.0.md
This snippet demonstrates the new `createApp` API, showing how to create an app instance, mount it to a DOM element, and unmount it. The `createApp` function now accepts the root component and optional props, and `app.mount()` takes only the root container.
```javascript
const app = createApp(RootComponent)
app.mount('#app')
app.unmount()
```
--------------------------------
### Build SFC Playground for Production
Source: https://github.com/vuejs/core/blob/main/packages-private/sfc-playground/README.md
Build the SFC Playground for production deployment from the repository root. This creates an optimized production build.
```shell
pnpm build-sfc-playground
```
--------------------------------
### Initialize and Mount a Vue Application using @vue/runtime-dom
Source: https://github.com/vuejs/core/blob/main/packages/runtime-dom/README.md
Demonstrates how to import createApp and h from the runtime-dom package to define a root component and mount it to a DOM element. It shows basic component rendering with a simple 'hello world' message.
```javascript
import { h, createApp } from '@vue/runtime-dom'
const RootComponent = {
render() {
return h('div', 'hello world')
},
}
createApp(RootComponent).mount('#app')
```
--------------------------------
### Initialize and Render Vue Component with @vue/runtime-test
Source: https://github.com/vuejs/core/blob/main/packages/runtime-test/README.md
This snippet demonstrates how to set up and render a basic Vue component using the `@vue/runtime-test` package. It imports core rendering utilities, defines a simple Vue application, creates a test root element, renders the component into it, and then logs the operations performed, showcasing the package's DOM-agnostic rendering capabilities for testing or custom renderer development.
```js
import { h, render, nodeOps, dumpOps } from '@vue/runtime-test'
const App = {
data() {
return {
msg: 'Hello World!',
}
},
render() {
return h('div', this.msg)
},
}
// root is of type `TestElement` as defined in src/nodeOps.ts
const root = nodeOps.createElement('div')
render(h(App), root)
const ops = dumpOps()
console.log(ops)
```
--------------------------------
### Initialize Vue.js 3.x Todo Application Instance
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/todomvc.html
This is the main Vue.js application instance, configuring the initial state, setting up watchers for local storage persistence, defining lifecycle hooks, computed properties for derived state, and methods for all core application logic such as adding, removing, editing, and filtering todos. It also includes a custom directive for input focus.
```javascript
Vue.createApp({
// app initial state
data: () => ({
todos: todoStorage.fetch(),
newTodo: '',
editedTodo: null,
visibility: 'all'
}),
// watch todos change for localStorage persistence
watch: {
todos: {
handler(todos) {
todoStorage.save(todos)
},
deep: true
}
},
mounted() {
window.addEventListener('hashchange', this.onHashChange)
this.onHashChange()
},
computed: {
filteredTodos() {
return filters[this.visibility](this.todos)
},
remaining() {
return filters.active(this.todos).length
},
allDone: {
get() {
return this.remaining === 0
},
set(value) {
this.todos.forEach(function (todo) {
todo.completed = value
})
}
}
},
// methods that implement data logic.
// note there's no DOM manipulation here at all.
methods: {
addTodo() {
var value = this.newTodo && this.newTodo.trim()
if (!value) {
return
}
this.todos.push({
id: todoStorage.uid++,
title: value,
completed: false
})
this.newTodo = ''
},
removeTodo(todo) {
this.todos.splice(this.todos.indexOf(todo), 1)
},
editTodo(todo) {
this.beforeEditCache = todo.title
this.editedTodo = todo
},
doneEdit(todo) {
if (!this.editedTodo) {
return
}
this.editedTodo = null
todo.title = todo.title.trim()
if (!todo.title) {
this.removeTodo(todo)
}
},
cancelEdit(todo) {
this.editedTodo = null
todo.title = this.beforeEditCache
},
removeCompleted() {
this.todos = filters.active(this.todos)
},
onHashChange() {
var visibility = window.location.hash.replace(/#\/?/, '')
if (filters[visibility]) {
this.visibility = visibility
} else {
window.location.hash = ''
this.visibility = 'all'
}
},
pluralize(n) {
return n === 1 ? 'item' : 'items'
}
},
directives: {
'todo-focus'(el, binding) {
if (binding.value) {
el.focus()
}
}
}
}).mount('#app')
```
--------------------------------
### Vue App Initialization with Modal Component
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/modal.html
Creates a Vue application instance with the Modal component registered, initializes reactive data for modal visibility state, and mounts the app to the DOM. The showModal property controls whether the modal is displayed.
```javascript
Vue.createApp({
components: { Modal },
data: () => ({
showModal: false
})
}).mount('#app')
```
--------------------------------
### Teleport Component Basic Usage
Source: https://github.com/vuejs/core/blob/main/changelogs/CHANGELOG-3.0.md
This snippet shows the updated syntax for the `` component, which replaces ``. It demonstrates using the `to` prop to specify the target element and the `disabled` prop for conditional rendering.
```html
hello
```
--------------------------------
### Initialize Monaco Editor with RequireJS
Source: https://github.com/vuejs/core/blob/main/packages-private/template-explorer/index.html
Loads the Monaco Editor main module using RequireJS and triggers the initialization function. This require call loads the editor.main module which provides the complete Monaco Editor API. The init function is injected during the build process to set up the editor instance.
```javascript
require(['vs/editor/editor.main'], init /* injected by build */)
```
--------------------------------
### Configure Vue CLI for Vue 3 Compat Mode
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Alias `vue` to `@vue/compat` and enable Vue 2 compatibility mode in the `vue-loader` options within `vue.config.js` for projects using Vue CLI.
```javascript
// vue.config.js
module.exports = {
chainWebpack: config => {
config.resolve.alias.set('vue', '@vue/compat')
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
return {
...options,
compilerOptions: {
compatConfig: {
MODE: 2,
},
},
}
})
},
}
```
--------------------------------
### Create Custom Renderer with Vue Runtime Core
Source: https://github.com/vuejs/core/blob/main/packages/runtime-core/README.md
Demonstrates how to build a custom renderer using createRenderer from @vue/runtime-core. The function accepts an object with platform-specific implementations (patchProp, insert, remove, createElement, etc.) and returns render and createApp functions. The render function provides low-level rendering control, while createApp creates an app instance with shared context across the component tree.
```typescript
import { createRenderer } from '@vue/runtime-core'
const { render, createApp } = createRenderer({
patchProp,
insert,
remove,
createElement,
// ...
})
// `render` is the low-level API
// `createApp` returns an app instance with configurable context shared
// by the entire app tree.
export { render, createApp }
export * from '@vue/runtime-core'
```
--------------------------------
### Vue.js Axis Label Component for Polygraph
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html
The `AxisLabel` Vue component is responsible for rendering individual labels on the polygraph's axes. It receives `stat` (data object), `index`, and `total` props. Using a computed property, it leverages the `valueToPoint` helper to dynamically calculate the `x` and `y` position for the `` SVG element, ensuring labels are correctly placed relative to their corresponding axis.
```javascript
const AxisLabel = {
template: '{{stat.label}}',
props: {
stat: Object,
index: Number,
total: Number
},
setup(props) {
return {
point: computed(() => valueToPoint(+props.stat.value + 10, props.index, props.total))
};
}
};
```
--------------------------------
### Enable Specific Vue Compat Features Globally (Vue 3 Default)
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Set `MODE: 3` in `configureCompat` to default the application to Vue 3 behavior, then explicitly enable desired Vue 2 compatibility features.
```js
import { configureCompat } from 'vue'
// default everything to Vue 3 behavior, and only enable compat
// for certain features
configureCompat({
MODE: 3,
FEATURE_ID_A: true,
FEATURE_ID_B: true,
})
```
--------------------------------
### Configure RequireJS Paths for Monaco Editor
Source: https://github.com/vuejs/core/blob/main/packages-private/template-explorer/index.html
Sets up RequireJS configuration to load Monaco Editor from CDN. This configuration specifies the base path for Monaco Editor modules, enabling the editor to load its dependencies from the unpkg CDN. The configuration must be called before requiring any Monaco modules.
```javascript
require.config({
paths: {
vs: 'https://unpkg.com/monaco-editor@0.20.0/min/vs'
}
})
```
--------------------------------
### Configure Vite for Vue 3 Compat Mode
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Alias `vue` to `@vue/compat` and enable Vue 2 compatibility mode in the Vue plugin's template compiler options within `vite.config.js` for projects using Vite.
```javascript
// vite.config.js
export default {
resolve: {
alias: {
vue: '@vue/compat',
},
},
plugins: [
vue({
template: {
compilerOptions: {
compatConfig: {
MODE: 2,
},
},
},
}),
],
}
```
--------------------------------
### CSS Transitions for List Item Animations
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/list.html
Defines CSS transition classes for enter, leave, and move animations with cubic-bezier easing. Includes opacity and scaleY transforms for enter/leave states, and absolute positioning for leave-active to ensure proper layout flow during animations.
```css
.container {
position: relative;
padding: 0;
}
.item {
width: 100%;
height: 30px;
background-color: #f3f3f3;
border: 1px solid #666;
box-sizing: border-box;
}
/* 1. declare transition */
.fade-move, .fade-enter-active, .fade-leave-active {
transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}
/* 2. declare enter from and leave to state */
.fade-enter-from, .fade-leave-to {
opacity: 0;
transform: scaleY(0.01) translate(30px, 0);
}
/* 3. ensure leaving items are taken out of layout flow so that moving animations can be calculated correctly. */
.fade-leave-active {
position: absolute;
}
```
--------------------------------
### Implement Markdown Editor Logic with Vue.js
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/markdown.html
This script initializes a Vue application that converts raw markdown input into HTML using the Marked library. It utilizes Lodash's debounce function to optimize performance by delaying updates to the input state until typing pauses.
```javascript
Vue.createApp({
data: () => ({
input: '# hello',
}),
computed: {
compiledMarkdown() {
return marked.marked(this.input, { sanitize: true })
},
},
methods: {
update: _.debounce(function (e) {
this.input = e.target.value
}, 50),
},
}).mount('#editor')
```
--------------------------------
### Detect Fragment and v-if Query Parameters
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-visible.html
Checks URL search parameters to determine if the component should render as a fragment or with v-if conditional rendering. These flags control different rendering strategies for testing SSR hydration scenarios.
```javascript
const isFragment = location.search.includes('?fragment')
const isVIf = location.search.includes('?v-if')
```
--------------------------------
### Initialize Vue.js Markdown Editor with Debounced Input
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/markdown.html
This Vue.js application sets up a basic markdown editor. It uses `ref` to manage the input text, `computed` to render the markdown using `marked.js` with sanitization, and `lodash.debounce` to limit the frequency of updates as the user types. The application mounts to an element with the ID `#editor`.
```javascript
const { ref, computed } = Vue
Vue.createApp({
setup() {
const input = ref('# hello')
const output = computed(() => marked.marked(input.value, { sanitize: true }),
)
const update = _.debounce(e => {
input.value = e.target.value
}, 50)
return {
input,
output,
update,
}
},
}).mount('#editor')
```
--------------------------------
### Configure Vue Compat Features Per Component
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Apply the `compatConfig` option within a component definition to control compatibility features specifically for that component, overriding global settings.
```js
export default {
compatConfig: {
MODE: 3, // opt-in to Vue 3 behavior for this component only
FEATURE_ID_A: true, // features can also be toggled at component level
},
// ...
}
```
--------------------------------
### Vue SFC Facade Module Structure
Source: https://github.com/vuejs/core/blob/main/packages/compiler-sfc/README.md
Demonstrates the facade module pattern used to import individual blocks of a Vue Single File Component. The facade module imports script, template, and style blocks separately with different query strings, allowing the build system to handle each as virtual modules. This enables separate HMR handling and independent transformation of each block.
```javascript
// main script
import script from '/project/foo.vue?vue&type=script'
// template compiled to render function
import { render } from '/project/foo.vue?vue&type=template&id=xxxxxx'
// css
import '/project/foo.vue?vue&type=style&index=0&id=xxxxxx'
// attach render function to script
script.render = render
// attach additional metadata
// some of these should be dev only
script.__file = 'example.vue'
script.__scopeId = 'xxxxxx'
// additional tooling-specific HMR handling code
// using __VUE_HMR_API__ global
export default script
```
--------------------------------
### Disable Specific Vue Compat Features Globally
Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md
Use `configureCompat` to disable individual compatibility features across the entire application, reverting them to Vue 3 behavior.
```js
import { configureCompat } from 'vue'
// disable compat for certain features
configureCompat({
FEATURE_ID_A: false,
FEATURE_ID_B: false,
})
```
--------------------------------
### Fetch GitHub Commits with Vue.js Composition API
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/commits.html
Creates a Vue.js application that fetches commits from the vuejs/core GitHub repository. Uses ref() for reactive state management, watchEffect() to trigger API calls when the branch changes, and includes utility functions for formatting commit messages and dates. The app supports switching between 'main' and 'v2-compat' branches.
```javascript
const { createApp, ref, watchEffect } = Vue
const API_URL = `https://api.github.com/repos/vuejs/core/commits?per_page=3&sha=`
const truncate = v => {
const newline = v.indexOf('\n')
return newline > 0 ? v.slice(0, newline) : v
}
const formatDate = v => v.replace(/T|Z/g, ' ')
createApp({
setup() {
const currentBranch = ref('main')
const commits = ref(null)
watchEffect(() => {
fetch(`${API_URL}${currentBranch.value}`)
.then(res => res.json())
.then(data => {
console.log(data)
commits.value = data
})
})
return {
branches: ['main', 'v2-compat'],
currentBranch,
commits,
truncate,
formatDate
}
}
}).mount('#demo')
```
--------------------------------
### Manage Todo Data with Local Storage in Vue.js
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/todomvc.html
This JavaScript utility object provides methods to interact with the browser's local storage for persisting todo items. It handles fetching existing todos, assigning unique IDs, and saving the current state of the todo list, ensuring data is retained across user sessions.
```javascript
const STORAGE_KEY = 'todos-vuejs-3.x'
const todoStorage = {
fetch() {
const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
todos.forEach((todo, index) => {
todo.id = index
})
todoStorage.uid = todos.length
return todos
},
save(todos) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
}
}
```
--------------------------------
### Define `renderToSimpleStream` function signature and interface in TypeScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This signature defines the `renderToSimpleStream` function, which renders a Vue application or VNode into a simple readable interface. It also defines the `SimpleReadable` interface, specifying `push` and `destroy` methods for handling stream chunks and errors in a custom streaming implementation.
```ts
function renderToSimpleStream(
input: App | VNode,
context: SSRContext,
options: SimpleReadable,
): SimpleReadable
interface SimpleReadable {
push(content: string | null): void
destroy(err: any): void
}
```
--------------------------------
### Define Layout Styles for Markdown Editor
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/markdown.html
These CSS rules define a side-by-side layout for the markdown editor, ensuring the textarea and preview pane occupy equal width and full height. It includes basic typography and styling for code elements within the preview.
```css
html, body, #editor {
margin: 0;
height: 100%;
font-family: 'Helvetica Neue', Arial, sans-serif;
color: #333;
}
textarea, #editor div {
display: inline-block;
overflow: auto;
width: 50%;
height: 100%;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0 20px;
}
textarea {
border: none;
border-right: 1px solid #ccc;
resize: none;
outline: none;
background-color: #f6f6f6;
font-size: 14px;
font-family: 'Monaco', courier, monospace;
padding: 20px;
}
code {
color: #f66;
}
```
--------------------------------
### TodoMVC Logic using Vue 3 Composition API
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/todomvc.html
Core application logic implementing state management with reactive(), persistence via localStorage, and reactive filtering using computed() properties. It also handles lifecycle hooks and custom directives.
```javascript
const { createApp, reactive, computed, watchEffect, onMounted, onUnmounted } = Vue
const STORAGE_KEY = 'todos-vuejs-3.x'
const todoStorage = {
fetch() {
const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
todos.forEach((todo, index) => { todo.id = index })
todoStorage.uid = todos.length
return todos
},
save(todos) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
},
}
const filters = {
all(todos) { return todos },
active(todos) { return todos.filter(todo => !todo.completed) },
completed(todos) { return todos.filter(todo => todo.completed) },
}
function pluralize(n) { return n === 1 ? 'item' : 'items' }
createApp({
setup() {
const state = reactive({
todos: todoStorage.fetch(),
editedTodo: null,
newTodo: '',
beforeEditCache: '',
visibility: 'all',
remaining: computed(() => filters.active(state.todos).length),
remainingText: computed(() => ` ${pluralize(state.remaining)} left`),
filteredTodos: computed(() => filters[state.visibility](state.todos)),
allDone: computed({
get: () => state.remaining === 0,
set: (value) => { state.todos.forEach(todo => { todo.completed = value }) },
}),
})
watchEffect(() => { todoStorage.save(state.todos) })
onMounted(() => {
window.addEventListener('hashchange', onHashChange)
onHashChange()
})
onUnmounted(() => { window.removeEventListener('hashchange', onHashChange) })
function onHashChange() {
const visibility = window.location.hash.replace(/#\/?/, '')
if (filters[visibility]) {
state.visibility = visibility
} else {
window.location.hash = ''
state.visibility = 'all'
}
}
function addTodo() {
const value = state.newTodo && state.newTodo.trim()
if (!value) return
state.todos.push({ id: todoStorage.uid++, title: value, completed: false })
state.newTodo = ''
}
function removeTodo(todo) { state.todos.splice(state.todos.indexOf(todo), 1) }
function editTodo(todo) { state.beforeEditCache = todo.title; state.editedTodo = todo }
function doneEdit(todo) {
if (!state.editedTodo) return
state.editedTodo = null
todo.title = todo.title.trim()
if (!todo.title) removeTodo(todo)
}
function cancelEdit(todo) { state.editedTodo = null; todo.title = state.beforeEditCache }
function removeCompleted() { state.todos = filters.active(state.todos) }
return { state, addTodo, removeTodo, editTodo, doneEdit, cancelEdit, removeCompleted }
},
directives: {
'todo-focus': (el, { value }) => { if (value) el.focus() },
},
}).mount('#app')
```
--------------------------------
### CSS Styling for Modal Overlay and Container
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/modal.html
Provides base styling for the modal mask (semi-transparent overlay), wrapper for vertical centering, and container with shadow and border-radius. Includes transitions for smooth opacity and transform effects.
```css
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: table;
transition: opacity 0.3s ease;
}
.modal-wrapper {
display: table-cell;
vertical-align: middle;
}
.modal-container {
width: 300px;
margin: 0px auto;
padding: 20px 30px;
background-color: #fff;
border-radius: 2px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
transition: all 0.3s ease;
font-family: Helvetica, Arial, sans-serif;
}
.modal-header h3 {
margin-top: 0;
color: #42b983;
}
.modal-body {
margin: 20px 0;
}
.modal-default-button {
float: right;
}
```
--------------------------------
### Define `renderToString` function signature in TypeScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This signature defines the `renderToString` function, which accepts a Vue application or VNode and an optional SSR context. It returns a Promise that resolves to the rendered HTML string, providing a fundamental method for server-side rendering.
```ts
function renderToString(
input: App | VNode,
context?: SSRContext,
): Promise
```
--------------------------------
### Vue.js SSR Conditional Hydration with hydrateOnMediaQuery
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-media.html
This snippet sets up a Vue.js SSR application where a component's hydration is controlled by a media query. The `AsyncComp` is defined using `defineAsyncComponent` and its `hydrate` option is set to `hydrateOnMediaQuery('(max-width:500px)')`. This ensures that the component's `onMounted` lifecycle hook (and thus interactivity) only runs when the browser window width is 500px or less. The `Comp` component itself is a simple button with a counter that logs 'hydrated' upon mounting.
```javascript
window.isHydrated = false;
const { createSSRApp, defineAsyncComponent, h, ref, onMounted, hydrateOnMediaQuery, } = Vue;
const Comp = {
props: {
value: Boolean,
},
setup(props) {
const count = ref(0);
onMounted(() => {
console.log('hydrated');
window.isHydrated = true;
});
return () => {
props.value;
return h('button', { onClick: () => count.value++ }, count.value);
};
},
};
const AsyncComp = defineAsyncComponent({
loader: () => Promise.resolve(Comp),
hydrate: hydrateOnMediaQuery('(max-width:500px)'),
});
createSSRApp({
setup() {
onMounted(() => {
window.isRootMounted = true;
});
const show = (window.show = ref(true));
return () => h(AsyncComp, { value: show.value });
},
}).mount('#app');
```
--------------------------------
### Define `renderToWebStream` function signature in TypeScript
Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md
This signature defines the `renderToWebStream` function, which takes a Vue application or VNode and an optional SSR context. It returns a standard Web ReadableStream, making it suitable for environments that fully support the Web Streams API.
```ts
function renderToWebStream(
input: App | VNode,
context?: SSRContext,
): ReadableStream
```
--------------------------------
### TreeItem Logic and App Initialization
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/tree.html
JavaScript implementation using Vue 3 Composition API. Defines the TreeItem component with reactive state and the root application with hierarchical data.
```javascript
const { reactive, computed, toRefs } = Vue
const TreeItem = {
name: 'TreeItem',
template: '#item-template',
props: {
model: Object,
},
setup(props) {
const state = reactive({
open: false,
isFolder: computed(() => {
return props.model.children && props.model.children.length
}),
})
function toggle() {
state.open = !state.open
}
function changeType() {
if (!state.isFolder) {
props.model.children = []
addChild()
state.open = true
}
}
function addChild() {
props.model.children.push({
name: 'new stuff'
})
}
return {
...toRefs(state),
toggle,
changeType,
addChild,
}
},
}
const treeData = {
name: 'My Tree',
children: [
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [
{
name: 'child folder',
children: [{ name: 'hello' }, { name: 'wat' }],
},
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [{ name: 'hello' }, { name: 'wat' }],
},
],
},
],
}
Vue.createApp({
components: {
TreeItem,
},
data: () => ({
treeData,
}),
}).mount('#demo')
```
--------------------------------
### Conditionally Set App HTML Content
Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-visible.html
Populates the app container with pre-rendered HTML based on query parameters. For fragments, it includes Vue comment nodes and multiple elements; for v-if, it renders an empty comment node. This simulates server-rendered content that will be hydrated.
```javascript
if (isFragment) {
document.getElementById('app').innerHTML = `onetwo`
} else if (isVIf) {
document.getElementById('app').innerHTML = ``
}
window.isHydrated = false
```
--------------------------------
### Style Markdown Editor Layout with CSS
Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/markdown.html
This CSS code provides the styling for a split-panel markdown editor layout. It sets basic page styles, defines the appearance of the `textarea` for input and a `div` for output, ensuring they are side-by-side and fill the height. Specific styles are applied to the `textarea` for a clean editor look and to `code` elements for highlighting.
```css
html, body, #editor {
margin: 0;
height: 100%;
font-family: 'Helvetica Neue', Arial, sans-serif;
color: #333;
}
textarea, #editor div {
display: inline-block;
overflow: auto;
width: 50%;
height: 100%;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0 20px;
}
textarea {
border: none;
border-right: 1px solid #ccc;
resize: none;
outline: none;
background-color: #f6f6f6;
font-size: 14px;
font-family: 'Monaco', courier, monospace;
padding: 20px;
}
code {
color: #f66;
}
```