### Initialize Vue.js Markdown Editor Application Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/markdown.html This JavaScript code initializes a Vue.js application that functions as a real-time Markdown editor. It manages user input, compiles Markdown to HTML using 'marked', and debounces updates to improve performance. Dependencies include Vue and lodash.debounce. ```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') ``` -------------------------------- ### Render Vue App with @vue/runtime-test Source: https://github.com/vuejs/core/blob/main/packages/runtime-test/README.md This example demonstrates how to use `@vue/runtime-test` to render a Vue application in a test environment. It imports core rendering utilities, defines a simple Vue component, renders it to a test element, and then dumps the operations performed, showcasing the package's functionality for DOM-agnostic testing. ```javascript 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 Application with Tree View Component Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/tree.html This JavaScript code initializes a new Vue.js application using `Vue.createApp()`. It registers the `TreeItem` component and provides the `treeData` as the initial data for the root instance. The application then mounts to the HTML element with the ID `demo`, rendering the tree view. ```javascript Vue.createApp({ components: { TreeItem, }, data: () => ({ treeData, }), }).mount('#demo') ``` -------------------------------- ### Vue.js Application Initialization and Data Setup Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/grid.html This JavaScript code initializes a Vue.js 3 application instance. It registers the `DemoGrid` component, defines initial application data such as `searchQuery`, `gridColumns`, and `gridData` (sample superhero data), and mounts the application to an HTML element with the ID `#demo`. ```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 Vue.js 3.x TodoMVC Application with Composition API Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/todomvc.html This comprehensive JavaScript block defines and initializes the main Vue.js 3.x application for a TodoMVC implementation. It leverages the Composition API within `setup()` to manage reactive state, computed properties for filtering and status display, and methods for all CRUD operations on todo items. It also includes `watchEffect` for local storage synchronization, lifecycle hooks (`onMounted`, `onUnmounted`) for hashchange event listeners, and a custom directive (`v-todo-focus`) for UI enhancements, finally mounting the application to the `#app` element. ```javascript createApp({ setup() { const state = reactive({ todos: todoStorage.fetch(), editedTodo: null, newTodo: '', beforeEditCache: '', visibility: 'all', remaining: computed(() => { return filters.active(state.todos).length }), remainingText: computed(() => { return ` ${pluralize(state.remaining)} left` }), filteredTodos: computed(() => { return filters[state.visibility](state.todos) }), allDone: computed({ get: function () { return state.remaining === 0 }, set: function (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, }) ``` -------------------------------- ### Update Vue and Compat Dependencies in package.json Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md This snippet shows the necessary changes in `package.json` to upgrade Vue to version 3.1, install `@vue/compat` of the same version, and replace `vue-template-compiler` with `@vue/compiler-sfc`. These updates are crucial for enabling the Vue 3 compatibility build. ```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" } ``` -------------------------------- ### Apply CSS Styles for Markdown Editor Layout Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/markdown.html This CSS code provides basic styling for the Markdown editor's layout and elements. It sets up a two-column layout for the 'textarea' and output 'div', ensures full height, and applies font styles and box-sizing properties for consistent rendering. It also styles 'textarea' and 'code' elements. ```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; } ``` -------------------------------- ### Initialize Vue 3 Application with Radar Chart and Controls Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html Sets up the main Vue 3 application instance, registers the `Polygraph` component, and manages the reactive state of the `stats` data. It includes functions to `add` new statistics and `remove` existing ones, demonstrating interactive data manipulation using the Composition API. ```javascript 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'); ``` -------------------------------- ### Vue 3 Polygraph (Radar Chart) Component Logic Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html Defines the JavaScript logic for the `Polygraph` component, including props, setup function with a computed `points` property, and component registration. It relies on the `valueToPoint` utility and the `AxisLabel` component, using a template referenced by `#polygraph-template`. ```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 } }; ``` -------------------------------- ### Adjusted Vue.js createApp API Usage Source: https://github.com/vuejs/core/blob/main/changelogs/CHANGELOG-3.0.md This code snippet illustrates the updated `createApp` API in Vue.js. The `createApp()` function now accepts the root component and optionally a props object. `app.mount()` takes a single argument for the root container, and `app.unmount()` no longer requires arguments. This change simplifies the application setup process. ```javascript const app = createApp(RootComponent) app.mount('#app') app.unmount() ``` -------------------------------- ### Vue 3 SSR Hydration Setup with Lazy-Loaded Async Component Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-idle.html This Vue.js 3 example sets up a Server-Side Rendered application that hydrates an asynchronous component. It uses `createSSRApp` for SSR, `defineAsyncComponent` for lazy loading, and `hydrateOnIdle` for efficient hydration when the browser is idle. The component displays a button with a counter that becomes interactive after hydration, logging messages to the console during its lifecycle. ```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 => { setTimeout(() => { console.log('resolve') resolve(Comp) requestIdleCallback(() => { console.log('busy') }) }, 10) }), hydrate: hydrateOnIdle(), }) createSSRApp({ render: () => h(AsyncComp), }).mount('#app') ``` -------------------------------- ### Handle absent props with Symbol default in Vue.js setup Source: https://github.com/vuejs/core/blob/main/changelogs/CHANGELOG-3.1.md This JavaScript code demonstrates a pattern to reliably check for the absence of a prop within the Vue 3 `setup()` function after changes in version 3.1.0. By using a unique `Symbol` as the default value for a prop, the component can distinguish between an explicitly passed `undefined` or `null` value and a completely absent prop. This is useful for maintaining specific logic that depends on whether a prop was provided or not, aligning with previous Vue 2 behaviors for prop absence checks. ```javascript const isAbsent = Symbol() export default { props: { foo: { default: isAbsent } }, setup(props) { if (props.foo === isAbsent) { // foo is absent } } } ``` -------------------------------- ### Example Vue SFC Facade Module Structure (JavaScript) Source: https://github.com/vuejs/core/blob/main/packages/compiler-sfc/README.md This code demonstrates the structure of a facade module generated by `@vue/compiler-sfc` for a Single File Component. It imports individual script, template (as a render function), and style blocks, then attaches the render function and additional metadata (like `__file`, `__scopeId`) to the exported script, facilitating features like HMR and scoped styling. ```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 ``` -------------------------------- ### Define Initial Global Statistics Data (JavaScript) Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html An array of objects defining the initial statistics for the radar chart. Each object contains a `label` and a `value`, representing an axis and its corresponding data point. This data is used to initialize the reactive state of the Vue application. ```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 } ]; ``` -------------------------------- ### Style Vue.js Tree View Components Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/tree.html This CSS snippet provides basic styling for the tree view components. It sets a default font and color for the body, defines a pointer cursor for interactive items, makes bold text for folder names, and styles unordered lists for proper indentation and list type. These styles enhance the visual presentation of the tree structure. ```css body { font-family: Menlo, Consolas, monospace; color: #444; } .item { cursor: pointer; } .bold { font-weight: bold; } ul { padding-left: 1em; line-height: 1.5em; list-style-type: dot; } ``` -------------------------------- ### JavaScript: Initial Polygraph Statistics Data Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/svg.html This JavaScript array defines the initial dataset for the polygraph. Each object represents a statistic with a `label` and a `value`, serving as the starting state for the application's reactive data. ```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 }, ] ``` -------------------------------- ### Define Vue.js Tree View Initial Data Structure Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/tree.html This JavaScript object represents the hierarchical data for the Vue.js tree view. It defines a `name` for each node and an optional `children` array to represent sub-nodes, allowing for nested structures. This `treeData` object serves as the initial state for the root of the tree component. ```javascript 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.js SSR Component Hydration based on Media Query Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-media.html This Vue.js example sets up a server-side rendered (SSR) application with an asynchronously loaded component. The `AsyncComp`'s hydration is deferred until the window width is less than or equal to 500px, as specified by `hydrateOnMediaQuery`. It also tracks hydration and root mount status using `window.isHydrated` and `window.isRootMounted` properties for debugging or testing purposes. The `Comp` component displays a button that increments a counter on click, indicating interactivity after hydration. ```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'); ``` -------------------------------- ### Vue 3 Polygraph (Radar Chart) HTML Template Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html The HTML template for the `Polygraph` component, designated by `#polygraph-template`. It renders an SVG `polygon` based on computed points, a central `circle`, and dynamically includes `AxisLabel` components for each statistic using a `v-for` loop. ```html ``` -------------------------------- ### Configure Webpack for Vue 3 Compatibility Mode Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md This webpack configuration aliases `vue` to `@vue/compat` in the `resolve.alias` section and sets the `compatConfig` to `MODE: 2` in the `vue-loader` options. This setup enables a plain webpack project to use the Vue 3 compatibility build, allowing it to interpret Vue 2 syntax. ```js // webpack.config.js module.exports = { resolve: { alias: { vue: '@vue/compat', }, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { compilerOptions: { compatConfig: { MODE: 2, }, }, }, }, ], }, } ``` -------------------------------- ### Configure Vue CLI for Vue 3 Compatibility Mode Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md This configuration for `vue.config.js` aliases `vue` to `@vue/compat` and enables Vue 2 compatibility mode (MODE: 2) within the Vue loader's compiler options. This setup allows a Vue CLI project to run Vue 2 code on a Vue 3 build environment. ```js // 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, }, }, } }) }, } ``` -------------------------------- ### Define Vue.js Recursive Tree Item Template Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/tree.html This template defines the structure for a single item in a recursive tree view component. It uses Vue directives like `:class`, `@click`, `@dblclick`, `v-if`, and `v-for` to render item name, toggle folder state, and allow adding new children. It recursively renders `tree-item` components for its children. ```html
  • {{model.name}} [{{open ? '-' : '+'}}]
  • ``` -------------------------------- ### Vue.js 3 SSR Custom Hydration with Async Component Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-custom.html This JavaScript code sets up a Vue.js 3 Server-Side Rendered (SSR) application, defining a basic counter component (`Comp`) and an asynchronous wrapper (`AsyncComp`). It implements a custom `hydrate` function for `AsyncComp` that delays the client-side hydration until a specific DOM element's click event is triggered. The script showcases manual control over hydration, lifecycle hooks (`onMounted`), and a teardown mechanism for the event listener. Global `window` properties are used to track hydration and mounting states. ```javascript window.isHydrated = false; const { createSSRApp, defineAsyncComponent, h, ref, onMounted } = Vue; const Comp = { setup() { const count = ref(0); onMounted(() => { console.log('hydrated'); window.isHydrated = true; }); return () => { return h('button', { onClick: () => count.value++ }, count.value); }; }, }; const AsyncComp = defineAsyncComponent({ loader: () => Promise.resolve(Comp), hydrate: (hydrate, el) => { const triggerEl = document.getElementById('custom-trigger'); triggerEl.addEventListener('click', hydrate, { once: true }); return () => { window.teardownCalled = true; triggerEl.removeEventListener('click', hydrate); }; }, }); const show = (window.show = ref(true)); createSSRApp({ setup() { onMounted(() => { window.isRootMounted = true; }); return () => (show.value ? h(AsyncComp) : 'off'); }, }).mount('#app'); ``` -------------------------------- ### Vue.js SSR Hydration Setup with `hydrateOnVisible` Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-visible.html This JavaScript snippet sets up a Vue.js server-side rendered application, defining an asynchronous component (`AsyncComp`) that leverages `hydrateOnVisible` to trigger hydration only when the component becomes visible in the viewport. It also includes logic to conditionally render HTML fragments or a `v-if` placeholder based on URL search parameters to test different hydration scenarios. A global `isHydrated` flag is set on mount to indicate successful hydration. ```javascript body { margin: 0; } const rootMargin = location.search.match(/rootMargin=(\d+)/)?.\[1\] ?? 0 const isFragment = location.search.includes('?fragment') const isVIf = location.search.includes('?v-if') if (isFragment) { document.getElementById('app').innerHTML = `onetwo` } else if (isVIf) { document.getElementById('app').innerHTML = `` } window.isHydrated = false const { createSSRApp, defineAsyncComponent, h, ref, onMounted, hydrateOnVisible, createCommentVNode, } = Vue 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 (isVIf) { return createCommentVNode('v-if', true) } else if (isFragment) { return [[h('span', 'one')], button, h('span', 'two')] } else { return button } } }, } const AsyncComp = defineAsyncComponent({ loader: () => Promise.resolve(Comp), hydrate: hydrateOnVisible({ rootMargin: rootMargin + 'px' }), }) createSSRApp({ setup() { onMounted(() => { window.isRootMounted = true }) return () => h(AsyncComp) }, }).mount('#app') ``` -------------------------------- ### Vue 3 Axis Label Component for Radar Chart Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/svg.html A Vue 3 component `AxisLabel` responsible for displaying the label of each axis on the radar chart. It calculates its position dynamically using a computed property based on the `valueToPoint` helper, ensuring proper placement relative to the chart's data. ```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)) }; } }; ``` -------------------------------- ### Define Vue.js Recursive TreeItem Component Logic Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/tree.html This JavaScript object defines the logic for the `TreeItem` Vue component. It includes props for `model` data, local `open` state, computed property `isFolder` to check for children, and methods like `toggle` to expand/collapse, `changeType` to convert an item to a folder, and `addChild` to add new sub-items. This component uses the options API and is designed for self-referencing in a recursive structure. ```javascript const TreeItem = { name: 'TreeItem', // necessary for self-reference template: '#item-template', props: { model: Object, }, data() { return { open: false, } }, computed: { isFolder() { return this.model.children && this.model.children.length }, }, methods: { toggle() { if (this.isFolder) { this.open = !this.open } }, changeType() { if (!this.isFolder) { this.model.children = [] this.addChild() this.open = true } }, addChild() { this.model.children.push({ name: 'new stuff', }) }, }, } ``` -------------------------------- ### Vue.js 3.x Todo App Core Imports and Utility Functions Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/todomvc.html This JavaScript snippet imports core functions from the Vue.js 3.x global object and defines essential helper utilities for the TodoMVC application. It includes `STORAGE_KEY` for local storage, `todoStorage` for data persistence, `filters` for task visibility, and a `pluralize` function for UI text. These components prepare the environment for the main Vue application. ```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 => { return !todo.completed }) }, completed(todos) { return todos.filter(function (todo) { return todo.completed }) }, } function pluralize(n) { return n === 1 ? 'item' : 'items' } ``` -------------------------------- ### Initialize Vue.js Markdown Editor Component Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/markdown.html This JavaScript snippet sets up a Vue.js application that functions as a real-time Markdown editor. It uses `ref` for reactive input, `computed` to convert markdown to HTML via `marked.marked` (with sanitization), and `lodash.debounce` to optimize updates, mounting the app to an element with 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') ``` -------------------------------- ### Initialize Vue.js application to display GitHub commits Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/commits.html This JavaScript code initializes a Vue.js application that connects to the GitHub API to fetch the latest commits for the 'vuejs/core' repository. It manages application state including selected branch and fetched commits, and provides methods for data fetching, commit message truncation, and date formatting. The application mounts to an HTML element with the ID 'demo'. ```javascript const API_URL = `https://api.github.com/repos/vuejs/core/commits?per_page=3&sha=` Vue.createApp({ data: () => ({ branches: ['main', 'v2-compat'], currentBranch: 'main', commits: null, }), created() { this.fetchData() }, watch: { currentBranch: 'fetchData', }, methods: { fetchData() { fetch(`${API_URL}${this.currentBranch}`) .then(res => res.json()) .then(data => { this.commits = data }) }, truncate(v) { const newline = v.indexOf('\n') return newline > 0 ? v.slice(0, newline) : v }, formatDate(v) { return v.replace(/T|Z/g, ' ') }, }, }).mount('#demo') ``` -------------------------------- ### Initialize Vue.js Application and Integrate Modal Component Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/modal.html This JavaScript code initializes a Vue 3 application, registers the `Modal` component, and mounts it to an HTML element with the ID `app`. It includes a `showModal` data property to manage the modal's visibility, showcasing how to integrate and control a custom component within a Vue instance. ```JavaScript Vue.createApp({ components: { Modal }, data: () => ({ showModal: false, }), }).mount('#app') ``` -------------------------------- ### Creating a Custom Vue Renderer with createRenderer Source: https://github.com/vuejs/core/blob/main/packages/runtime-core/README.md This snippet illustrates how to utilize the `createRenderer` function from `@vue/runtime-core` to construct a custom Vue renderer. It demonstrates the essential properties like `patchProp`, `insert`, `remove`, and `createElement` that need to be provided to configure the renderer's behavior. The resulting `render` and `createApp` functions are then exported for use in the custom rendering environment. ```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 3.x Todo App Data, Watchers, and Hash Routing Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/todomvc.html Initializes the Vue.js 3.x application with its core `data` properties, including the list of todos, input states, and current visibility filter. It sets up a deep `watch` on the `todos` array for automatic local storage persistence and uses the `mounted` hook to listen for and react to URL hash changes, enabling filtering based on routing. ```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() }, ``` -------------------------------- ### Initialize Vue.js Application with Data Grid Component Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/grid.html This JavaScript code initializes a Vue 3 application, registers the `DemoGrid` component, and defines the application's root data. It includes a `searchQuery`, `gridColumns` for defining the table structure, and `gridData` as the initial dataset. The application is then mounted to the HTML element with ID 'demo'. ```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') ``` -------------------------------- ### CSS for List Item Styling and Transitions Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/list.html This CSS provides basic styling for a container and individual list items. It defines transition properties using Vue's convention for list transitions, including `fade-move`, `fade-enter-active`, `fade-leave-active`, `fade-enter-from`, and `fade-leave-to` classes to create smooth animations for items entering, leaving, or moving within the list. ```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; } ``` -------------------------------- ### JavaScript: Use renderToSimpleStream for Custom Streaming Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md Demonstrates how to use `renderToSimpleStream` with a custom `SimpleReadable` object to handle streamed content. The `push` method receives chunks, and `destroy` handles errors, allowing for flexible custom stream processing and aggregation. ```js let res = '' renderToSimpleStream( app, {}, { push(chunk) { if (chunk === null) { // done console(`render complete: ${res}`) } else { res += chunk } }, destroy(err) { // error encountered }, }, ) ``` -------------------------------- ### JavaScript: Render Vue App to String Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md Demonstrates how to use `renderToString` to render a Vue SSR application to an HTML string asynchronously. It requires `createSSRApp` from `vue` and `renderToString` from `@vue/server-renderer` to initialize the app and perform rendering. ```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) })() ``` -------------------------------- ### Configure Vue.js global compatibility to enable specific features while defaulting to Vue 3 Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md Set the global `MODE` to 3 within `configureCompat` to default the entire application to Vue 3 behavior, then selectively enable specific Vue 2 compatibility features as needed for a smoother migration. ```javascript 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, }) ``` -------------------------------- ### Vue.js Application for Dynamic List Operations Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/transition/list.html This JavaScript snippet defines a Vue 3 application that manages a list of numbers. It includes utility functions to initialize items and an `Item` component. The main application features methods to insert a new item at a random position, reset the list, shuffle items (implying a dependency like Lodash for `_shuffle`), and remove a specific item from the list. ```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') ``` -------------------------------- ### Configure Vue.js global compatibility to disable specific features Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md Use the `configureCompat` function to globally disable specific compatibility features, effectively forcing Vue 3 behavior for those features across the entire application during migration. ```javascript import { configureCompat } from 'vue' // disable compat for certain features configureCompat({ FEATURE_ID_A: false, FEATURE_ID_B: false, }) ``` -------------------------------- ### Configure Vue.js compatibility options for a single component Source: https://github.com/vuejs/core/blob/main/packages/vue-compat/README.md Apply compatibility settings on a per-component basis using the `compatConfig` option within a component definition. This allows fine-grained control, enabling specific components to opt into Vue 3 behavior or toggle features independently. ```javascript 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.js: Main Application Instance with Data Management Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/svg.html Initializes the main Vue.js application, registering the `Polygraph` component. It manages the application's state, including `newLabel` for input and the `stats` array. Methods are provided to `add` a new statistic and `remove` an existing one, with a minimum stat count enforced before deletion. The app is mounted to the `#demo` element. ```javascript 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') ``` -------------------------------- ### Initialize Vue.js SSR App with Async Component and Interactive Hydration Source: https://github.com/vuejs/core/blob/main/packages/vue/__tests__/e2e/hydration-strat-interaction.html This comprehensive snippet demonstrates setting up a Vue 3 SSR application. It includes conditional HTML injection for fragment testing, imports necessary Vue APIs, defines a stateful component (`Comp`) with `onMounted` and a counter, and wraps it in an `AsyncComp` configured for interactive hydration on 'click' or 'wheel' events using `hydrateOnInteraction`. The root application then mounts this asynchronous component to the '#app' element. ```javascript const isFragment = location.search.includes('?fragment') if (isFragment) { document.getElementById('app').innerHTML = "onetwo" } window.isHydrated = false const { createSSRApp, defineAsyncComponent, h, ref, onMounted, hydrateOnInteraction, } = Vue 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 } } }, } const AsyncComp = defineAsyncComponent({ loader: () => Promise.resolve(Comp), hydrate: hydrateOnInteraction(['click', 'wheel']), }) createSSRApp({ setup() { onMounted(() => { window.isRootMounted = true }) return () => h(AsyncComp) }, }).mount('#app') ``` -------------------------------- ### Initialize Vue.js App to Display GitHub Commits Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/composition/commits.html This Vue.js application fetches and displays the latest commits from the 'vuejs/core' GitHub repository. It utilizes `createApp`, `ref`, and `watchEffect` from Vue to manage state and reactively update commit data based on the selected branch. The code includes utility functions for truncating commit messages and formatting dates for display. ```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') ``` -------------------------------- ### Vue.js 3.x Todo App Custom Directives and Mounting Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/todomvc.html Defines a custom Vue.js `directive` named `todo-focus` that programmatically sets focus on an element when its binding value is true. This snippet also includes the final call to `.mount('#app')`, which attaches the entire Vue application instance to the specified DOM element. ```javascript directives: { 'todo-focus'(el, binding) { if (binding.value) { el.focus() } }, }, }).mount('#app') ``` -------------------------------- ### Vue.js 3.x Local Storage Utility for Todos Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/todomvc.html Defines the `todoStorage` object, which handles persistence of todo items to and from the browser's local storage. It includes methods for `fetch` (parsing JSON and assigning unique IDs) and `save` (stringifying JSON) to ensure data integrity across 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)) }, } ``` -------------------------------- ### TypeScript: renderToSimpleStream Function Signature and Interface Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md Defines the signature for the `renderToSimpleStream` function and its `SimpleReadable` interface, providing a basic streaming mechanism with `push` for content chunks and `destroy` for error handling. This offers a flexible, low-level streaming interface. ```ts function renderToSimpleStream( input: App | VNode, context: SSRContext, options: SimpleReadable, ): SimpleReadable interface SimpleReadable { push(content: string | null): void destroy(err: any): void } ``` -------------------------------- ### Apply basic CSS styling for commit list display Source: https://github.com/vuejs/core/blob/main/packages/vue/examples/classic/commits.html This CSS code provides basic styling for the commit list display, including font family for the main container, link styling, list item spacing, and bolding for author and date information. It ensures readability and a clean presentation of the commit data. ```css #demo { font-family: 'Helvetica', Arial, sans-serif; } a { text-decoration: none; color: #f66; } li { line-height: 1.5em; margin-bottom: 20px; } .author, .date { font-weight: bold; } ``` -------------------------------- ### JavaScript: Render Vue App to Web ReadableStream Source: https://github.com/vuejs/core/blob/main/packages/server-renderer/README.md Shows how to render a Vue application to a Web ReadableStream, typically used for constructing a `Response` object in environments supporting Web Streams like service workers or certain serverless functions. This allows for streaming responses in a web-native way. ```js // inside an environment with ReadableStream support return new Response(renderToWebStream(app)) ```