1. Project Overview & Quickstart (nexmoe/LICENSE)
LICENSE
Open-source repository nexmoe/LICENSE
Repository Details
- Repository: nexmoe/LICENSE
- Primary Language: Code
Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.
2. Official Technical Reference & Guides (nexmoe/docs)
File: README.md
vuejs.org
This is the WIP branch of the brand new vuejs.org. The content is under heavy updates and re-organization so please refrain from submitting PRs to this branch until we have removed this notice.
Contributing
This site is built with VitePress and depends on @vue/theme. Site content is written in Markdown format located in src. For simple edits, you can directly edit the file on GitHub and generate a Pull Request.
For local development, pnpm is preferred as package manager:
pnpm i
pnpm run devWorking on the content
See VitePress docs on supported Markdown Extensions and the ability to use Vue syntax inside markdown.
See the Writing Guide for our rules and recommendations on writing and maintaining documentation content.
Working on the theme
If changes need to made for the theme, check out the instructions for developing the theme alongside the docs.
File: src/guide/extras/animation.md
Animation Techniques
Vue provides the ](/guide/built-ins/transition.html) and [ components for handling enter / leave and list transitions. However, there are many other ways of using animations on the web, even in a Vue application. Here we will discuss a few additional techniques.
Class-based Animations
For elements that are not entering / leaving the DOM, we can trigger animations by dynamically adding a CSS class:
const disabled = ref(false)
function warnDisabled() {
disabled.value = true
setTimeout(() => {
disabled.value = false
}, 1500)
}export default {
data() {
return {
disabled: false
}
},
methods: {
warnDisabled() {
this.disabled = true
setTimeout(() => {
this.disabled = false
}, 1500)
}
}
}Click me
This feature is disabled!.shake {
animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
transform: translate3d(0, 0, 0);
}
@keyframes shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}State-driven Animations
Some transition effects can be applied by interpolating values, for instance by binding a style to an element while an interaction occurs. Take this example for instance:
const x = ref(0)
function onMousemove(e) {
x.value = e.clientX
}export default {
data() {
return {
x: 0
}
},
methods: {
onMousemove(e) {
this.x = e.clientX
}
}
}Move your mouse across this div...
x: {{ x }}.movearea {
transition: 0.3s background-color ease;
}In addition to color, you can also use style bindings to animate transform, width, or height. You can even animate SVG paths using spring physics - after all, they are all attribute data bindings:
Animating with Watchers
With some creativity, we can use watchers to animate anything based on some numerical state. For example we can animate the number itself:
import { ref, reactive, watch } from 'vue'
import gsap from 'gsap'
const number = ref(0)
const tweened = reactive({
number: 0
})
watch(number, (n) => {
gsap.to(tweened, { duration: 0.5, number: Number(n) || 0 })
})import gsap from 'gsap'
export default {
data() {
return {
number: 0,
tweened: 0
}
},
watch: {
number(n) {
gsap.to(this, { duration: 0.5, tweened: Number(n) || 0 })
}
}
}Type a number:
{{ tweened.number.toFixed(0) }}File: src/guide/extras/composition-api-faq.md
outline: deep
Composition API FAQ
:::tip
This FAQ assumes prior experience with Vue - in particular, experience with Vue 2 while primarily using Options API.
:::
What is Composition API?
Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It is an umbrella term that covers the following APIs:
Reactivity API, e.g.
ref()andreactive(), that allows us to directly create reactive state, computed state, and watchers.Lifecycle Hooks, e.g.
onMounted()andonUnmounted(), that allow us to programmatically hook into the component lifecycle.Dependency Injection, i.e.
provide()andinject(), that allow us to leverage Vue's dependency injection system while using Reactivity APIs.
Composition API is a built-in feature of Vue 3, and is currently available to Vue 2 via the officially maintained @vue/composition-api plugin. In Vue 3, it is also primarily used together with the <script setup> syntax in Single-File Components. Here's a basic example of a component using Composition API:
<script setup>
import { ref, onMounted } from 'vue'
// reactive state
const count = ref(0)
// functions that mutate state and trigger updates
function increment() {
count.value++
}
// lifecycle hooks
onMounted(() => {
console.log(`The initial count is ${count.value}.`)
})
</script>
<template>
Count is: {{ count }}
</template>Despite an API style based on function composition, Composition API is NOT functional programming. Composition API is based on Vue's mutable, fine-grained reactivity paradigm, whereas functional programming emphasizes immutability.
If you are interested in learning how to use Vue with Composition API, you can set the site-wide API preference to Composition API using the toggle at the top of the left sidebar, and then go through the guide from the beginning.
Why Composition API?
Better Logic Reuse
The primary advantage of Composition API is that it enables clean, efficient logic reuse in the form of Composable functions. It solves all the drawbacks of mixins, the primary logic reuse mechanism for Options API.
Composition API's logic reuse capability has given rise to impressive community projects such as VueUse, an ever-growing collection of composable utilities. It also serves as a clean mechanism for easily integrating stateful third-party libraries into Vue's reactivity system, for example RxJS.
More Flexible Code Organization
Many users love that we write organized code by default with Options API: everything has its place based on the option it falls under. However, Options API poses serious limitations when a single component's logic grows beyond a certain complexity threshold. This limitation is particularly prominent in components that need to deal with multiple logical concerns, which we have witnessed first hand in many production Vue 2 apps.
Take the folder explorer component from Vue CLI's GUI as an example: this component is responsible for the following logical concerns:
- Tracking current folder state and displaying its content
- Handling folder navigation (opening, closing, refreshing...)
- Handling new folder creation
- Toggling show favorite folders only
- Toggling show hidden folders
- Handling current working directory changes
The original version of the component was written in Options API. If we give each line of code a color based on the logical concern it is dealing with, this is how it looks:
Notice how code dealing with the same logical concern is forced to be split under different options, located in different parts of the file. In a component that is several hundred lines long, understanding and navigating a single logical concern requires constantly scrolling up and down the file, making it much more difficult than it should be. In addition, if we ever intend to extract a logical concern into a reusable utility, it takes quite a bit of work to find and extract the right pieces of code from different parts of the file.
Here's the same component, before and after the refactor into Composition API:
Notice how the code related to the same logical concern can now be grouped together: we no longer need to jump between different options blocks while working on a specific logical concern. Moreover, we can now move a group of code into an external file with minimal effort, since we no longer need to shuffle the code around in order to extract them. This reduced friction for refactoring is key to the long-term maintainability in large codebases.
Better Type Inference
In recent years, more and more frontend developers are adopting TypeScript as it helps us write more robust code, make changes with more confidence, and provides a great development experience with IDE support. However, the Options API, originally conceived in 2013, was designed without type inference in mind. We had to implement some absurdly complex type gymnastics to make type inference work with the Options API. Even with all this effort, type inference for Options API can still break down for mixins and dependency injection.
This had led many developers who wanted to use Vue with TS to lean towards Class API powered by vue-class-component. However, a class-based API heavily relies on ES decorators, a language feature that was only a stage 2 proposal when Vue 3 was being developed in 2019. We felt it was too risky to base an official API on an unstable proposal. Since then, the decorators proposal has gone through yet another complete overhaul, and has yet to reach stage 3 as of this writing. In addition, class-based API suffers from logic reuse and organization limitations similar to Options API.
In comparison, Composition API utilizes mostly plain variables and functions, which are naturally type friendly. Code written in Composition API can enjoy full type inference with little need for manual type hints. Most of the time, Composition API code will look largely identical in TypeScript and plain JavaScript. This also makes it possible for plain JavaScript users to benefit from partial type inference.
Smaller Production Bundle and Less Overhead
Code written in Composition API and <script setup> is also more efficient and minification-friendly than Options API equivalent. This is because the template in a <script setup> component is compiled as a function inlined in the same scope of the <script setup> code. Unlike property access from this, the compiled template code can directly access variables declared inside <script setup>, without an instance proxy in between. This also leads to better minification because all the variable names can be safely shortened.
Relationship with Options API
Does Composition API cover all use cases?
Yes in terms of stateful logic. When using Composition API, there are only a few options that may still be needed: props, emits, name, and inheritAttrs. If using <script setup>, then inheritAttrs is typically the only option that may require a separate normal <script> block.
If you intend to exclusively use Composition API (along with the options listed above), you can shave a few kbs off your production bundle via a compile-time flag that drops Options API related code from Vue. Note this also affects Vue components in your dependencies.
Can I use both APIs together?
Yes. You can use Composition API via the setup() option in an Options API component.
However, we only recommend doing so if you have an existing Options API codebase that needs to integrate with new features / external libraries written with Composition API.
Will Options API be deprecated?
No, we do not have any plan to do so. Options API is an integral part of Vue and the reason many developers love it. We also realize that many of the benefits of Composition API only manifest in larger-scale projects, and Options API remains a solid choice for many low-to-medium-complexity scenarios.
Relationship with Class API
We no longer recommend using Class API with Vue 3, given that Composition API provides great TypeScript integration with additional logic reuse and code organization benefits.
Comparison with React Hooks
Composition API provides the same level of logic composition capabilities as React Hooks, but with some important differences.
React Hooks are invoked repeatedly every time a component updates. This creates a number of caveats that can confuse even seasoned React developers. It also leads to performance optimization issues that can severely affect development experience. Here are some examples:
Hooks are call-order sensitive and cannot be conditional.
Variables declared in a React component can be captured by a hook closure and become "stale" if the developer fails to pass in the correct dependencies array. This leads to React developers relying on ESLint rules to ensure correct dependencies are passed. However, the rule is often not smart enough and over-compensates for correctness, which leads to unnecessary invalidation and headaches when edge cases are encountered.
Expensive computations require the use of
useMemo, which again requires manually passing in the correct dependencies array.Event handlers passed to child components cause unnecessary child updates by default, and require explicit
useCallbackas an optimization. This is almost always needed, and again requires a correct dependencies array. Neglecting this leads to over-rendering apps by default and can cause performance issues without realizing it.The stale closure problem, combined with Concurrent features, makes it difficult to reason about when a piece of hooks code is run, and makes working with mutable state that should persist across renders (via
useRef) cumbersome.
In comparison, Vue Composition API:
Invokes
setup()or<script setup>code only once. This makes the code align better with the intuitions of idiomatic JavaScript usage as there are no stale closures to worry about. Composition API calls are also not sensitive to call order and can be conditional.Vue's runtime reactivity system automatically collects reactive dependencies used in computed properties and watchers, so there's no need to manually declare dependencies.
No need to manually cache callback functions to avoid unnecessary child updates. In general, Vue's fine-grained reactivity system ensures child components only update when they need to. Manual child-update optimizations are rarely a concern for Vue developers.
We acknowledge the creativity of React Hooks, and it is a major source of inspiration for Composition API. However, the issues mentioned above do exist in its design and we noticed Vue's reactivity model happens to provide a way around them.
File: src/guide/extras/reactivity-in-depth.md
outline: deep
Reactivity in Depth
One of Vueโs most distinct features is the unobtrusive reactivity system. Component state are reactive JavaScript objects. When you modify them, the view updates. It makes state management simple and intuitive, but itโs also important to understand how it works to avoid some common gotchas. In this section, we are going to dig into some of the lower-level details of Vueโs reactivity system.
What is Reactivity?
This term comes up in programming quite a bit these days, but what do people mean when they say it? Reactivity is a programming paradigm that allows us to adjust to changes in a declarative manner. The canonical example that people usually show, because itโs a great one, is an Excel spreadsheet:
Here cell A2 is defined via a formula of = A0 + A1 (you can click on A2 to view or edit the formula), so the spreadsheet gives us 3. No surprises there. But if you update A0 or A1, you'll notice that A2 automagically updates too.
JavaScript doesnโt usually work like this. If we were to write something comparable in JavaScript:
let A0 = 1
let A1 = 2
let A2 = A0 + A1
console.log(A2) // 3
A0 = 2
console.log(A2) // Still 3When we mutate A0, A2 does not change automatically.
So how would we do this in JavaScript? First, in order to re-run the code that updates A2, let's wrap it in a function:
let A2
function update() {
A2 = A0 + A1
}Then, we need to define a few terms:
The
update()function produces a side effect, or effect for short, because it modifies the state of the program.A0andA1are considered dependencies of the effect, as their values are used to perform the effect. The effect is said to be a subscriber to its dependencies.
What we need is a magic function that can invoke update() (the effect) whenever A0 or A1 (the dependencies) change:
whenDepsChange(update)This whenDepsChange() function has the following tasks:
Track when a variable is read. E.g. when evaluating the expression
A0 + A1, bothA0andA1are read.If a variable is read when there is a currently running effect, make that effect a subscriber to that variable. E.g. because
A0andA1are read whenupdate()is being executed,update()becomes a subscriber to bothA0andA1after the first call.Detect when a variable is mutated. E.g. when
A0is assigned a new value, notify all its subscriber effects to re-run.
How Reactivity Works in Vue
We can't really track the reading and writing of local variables like in the example. There's just no mechanism for doing that in vanilla JavaScript. What we can do though, is intercept the reading and writing of object properties.
There are two ways of intercepting property access in JavaScript: getter/setters and Proxies. Vue 2 used getter/setters exclusively due to browser support limitations. In Vue 3, Proxies are used for reactive objects and getter/setters are used for refs. Here's some pseudo-code that illustrates how they work:
function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
track(target, key)
return target[key]
},
set(target, key, value) {
trigger(target, key)
target[key] = value
}
})
}
function ref(value) {
const refObject = {
get value() {
track(refObject, 'value')
return value
},
set value(newValue) {
trigger(refObject, 'value')
value = newValue
}
}
return refObject
}:::tip
Code snippets here and below are meant to explain the core concepts in the simplest form possible, so many details are omitted, and edge cases ignored.
:::
This explains a few limitations of reactive objects that we have discussed in the fundamentals section:
When you assign or destructure a reactive object's property to a local variable, the reactivity is "disconnected" because access to the local variable no longer triggers the get / set proxy traps.
The returned proxy from
reactive(), although behaving just like the original, has a different identity if we compare it to the original using the===operator.
Inside track(), we check whether there is a currently running effect. If there is one, we lookup the subscriber effects (stored in a Set) for the property being tracked, and add the effect to the Set:
// This will be set right before an effect is about
// to be run. We'll deal with this later.
let activeEffect
function track(target, key) {
if (activeEffect) {
const effects = getSubscribersForProperty(target, key)
effects.add(activeEffect)
}
}Effect subscriptions are stored in a global WeakMap<target, Map<key, Set<effect>>> data structure. If no subscribing effects Set was found for a property (tracked for the first time), it will be created. This is what the getSubscribersForProperty() function does, in short. For simplicity, we will skip its details.
Inside trigger(), we again lookup the subscriber effects for the property. But this time we invoke them instead:
function trigger(target, key) {
const effects = getSubscribersForProperty(target, key)
effects.forEach((effect) => effect())
}Now let's circle back to the whenDepsChange() function:
function whenDepsChange(update) {
const effect = () => {
activeEffect = effect
update()
activeEffect = null
}
effect()
}It wraps the raw update function in an effect that sets itself as the current active effect before running the actual update. This enables track() calls during the update to locate the current active effect.
At this point, we have created an effect that automatically tracks its dependencies, and re-runs whenever a dependency changes. We call this a Reactive Effect.
Vue provides an API that allows you to create reactive effects: watchEffect(). In fact, you may have noticed that it works pretty similarly to the magical whenDepsChange() in the example. We can now rework the original example using actual Vue APIs:
import { ref, watchEffect } from 'vue'
const A0 = ref(0)
const A1 = ref(1)
const A2 = ref()
watchEffect(() => {
// tracks A0 and A1
A2.value = A0.value + A1.value
})
// triggers the effect
A0.value = 2Using a reactive effect to mutate a ref isn't the most interesting use case - in fact, using a computed property makes it more declarative:
import { ref, computed } from 'vue'
const A0 = ref(0)
const A1 = ref(1)
const A2 = computed(() => A0.value + A1.value)
A0.value = 2Internally, computed manages its invalidation and re-computation using a reactive effect.
So what's an example of a common and useful reactive effect? Well, updating the DOM! We can implement simple "reactive rendering" like this:
import { ref, watchEffect } from 'vue'
const count = ref(0)
watchEffect(() => {
document.body.innerHTML = `count is: ${count.value}`
})
// updates the DOM
count.value++In fact, this is pretty close to how a Vue component keeps the state and the DOM in sync - each component instance creates a reactive effect to render and update the DOM. Of course, Vue components use much more efficient ways to update the DOM than innerHTML. This is discussed in Rendering Mechanism.
The ref(), computed() and watchEffect() APIs are all part of the Composition API. If you have only been using Options API with Vue so far, you'll notice that Composition API is closer to how Vue's reactivity system works under the hood. In fact, in Vue 3 the Options API is implemented on top of the Composition API. All property access on the component instance (this) triggers getter/setters for reactivity tracking, and options like watch and computed invoke their Composition API equivalents internally.
Runtime vs. Compile-time Reactivity
Vue's reactivity system is primarily runtime-based: the tracking and triggering are all performed while the code is running directly in the browser. The pros of runtime reactivity is that it can work without a build step, and there are fewer edge cases. On the other hand, this makes it constrained by the syntax limitations of JavaScript.
We have already encountered a limitation in the previous example: JavaScript does not provide a way for us to intercept the reading and writing of local variables, so we have to always access reactive state as object properties, using either reactive objects or refs.
We have been experimenting with the Reactivity Transform feature to reduce the code verbosity:
let A0 = $ref(0)
let A1 = $ref(1)
// track on variable read
const A2 = $computed(() => A0 + A1)
// trigger on variable write
A0 = 2This snippet compiles into exactly what we'd have written without the transform, by automatically appending .value after references to the variables. With Reactivity Transform, Vue's reactivity system becomes a hybrid one.
Reactivity Debugging
It's great that Vue's reactivity system automatically tracks dependencies, but in some cases we may want to figure out exactly what is being tracked, or what is causing a component to re-render.
Component Debugging Hooks
We can debug what dependencies are used during a component's render and which dependency is triggering an update using the renderTracked``onRenderTracked and renderTriggered``onRenderTriggered lifecycle hooks. Both hooks will receive a debugger event which contains information on the dependency in question. It is recommended to place a debugger statement in the callbacks to interactively inspect the dependency:
<script setup>
import { onRenderTracked, onRenderTriggered } from 'vue'
onRenderTracked((event) => {
debugger
})
onRenderTriggered((event) => {
debugger
})
</script>export default {
renderTracked(event) {
debugger
},
renderTriggered(event) {
debugger
}
}:::tip
Component debug hooks only work in development mode.
:::
The debug event objects have the following type:
type DebuggerEvent = {
effect: ReactiveEffect
target: object
type:
| TrackOpTypes /* 'get' | 'has' | 'iterate' */
| TriggerOpTypes /* 'set' | 'add' | 'delete' | 'clear' */
key: any
newValue?: any
oldValue?: any
oldTarget?: Map<any, any> | Set<any>
}Computed Debugging
We can debug computed properties by passing computed() a second options object with onTrack and onTrigger callbacks:
onTrackwill be called when a reactive property or ref is tracked as a dependency.onTriggerwill be called when the watcher callback is triggered by the mutation of a dependency.
Both callbacks will receive debugger events in the same format as component debug hooks:
const plusOne = computed(() => count.value + 1, {
onTrack(e) {
// triggered when count.value is tracked as a dependency
debugger
},
onTrigger(e) {
// triggered when count.value is mutated
debugger
}
})
// access plusOne, should trigger onTrack
console.log(plusOne.value)
// mutate count.value, should trigger onTrigger
count.value++:::tiponTrack and onTrigger computed options only work in development mode.
:::
Watcher Debugging
Similar to computed(), watchers also support the onTrack and onTrigger options:
watch(source, callback, {
onTrack(e) {
debugger
},
onTrigger(e) {
debugger
}
})
watchEffect(callback, {
onTrack(e) {
debugger
},
onTrigger(e) {
debugger
}
}):::tiponTrack and onTrigger watcher options only work in development mode.
:::
Integration with External State Systems
Vue's reactivity system works by deeply converting plain JavaScript objects into reactive proxies. The deep conversion can be unnecessary or sometimes unwanted when integrating with external state management systems (e.g. if an external solution also uses Proxies).
The general idea of integrating Vue's reactivity system with an external state management solution is to hold the external state in a shallowRef. A shallow ref is only reactive when its .value property is accessed - the inner value is left intact. When the external state changes, replace the ref value to trigger updates.
Immutable Data
If you are implementing a undo / redo feature, you likely want to take a snapshot of the application's state on every user edit. However, Vue's mutable reactivity system isn't best suited for this if the state tree is large, because serializing the entire state object on every update can be expensive in terms of both CPU and memory costs.
Immutable data structures solve this by never mutating the state objects - instead, it creates new objects that share the same, unchanged parts with old ones. There are different ways of using immutable data in JavaScript, but we recommend using Immer with Vue because it allows you to use immutable data while keeping the more ergonomic, mutable syntax.
We can integrate Immer with Vue via a simple composable:
import produce from 'immer'
import { shallowRef } from 'vue'
export function useImmer(baseState) {
const state = shallowRef(baseState)
return {
state,
update(updater) {
state.value = produce(state.value, updater)
}
}
}State Machines
State Machine is a model for describing all the possible states an application can be in, and all the possible ways it can transition from one state to another. While it may be overkill for simple components, it can help make complex state flows more robust and manageable.
One of the most popular state machine implementations in JavaScript is XState. Here's a composable that integrates with it:
import { createMachine, interpret } from 'xstate'
import { shallowRef } from 'vue'
export function useMachine(options) {
const machine = createMachine(options)
const state = shallowRef(machine.initialState)
const service = interpret(machine)
.onTransition((newState) => (state.value = newState))
.start()
return {
state,
send(event) {
service.send(event)
}
}
}RxJS
RxJS is a library for working with asynchronous event streams. The VueUse library provides the @vueuse/rxjs add-on for connecting RxJS streams with Vue's reactivity system.
File: src/guide/extras/reactivity-transform.md
Reactivity Transform
:::warning Experimental Feature
Reactivity Transform is currently an experimental feature. It is disabled by default and requires explicit opt-in. It may also change before being finalized. To stay up-to-date, keep an eye on its proposal and discussion on GitHub.
:::
:::tip Composition-API-specific
Reactivity Transform is a Composition-API-specific feature and requires a build step.
:::
Refs vs. Reactive Variables
Ever since the introduction of the Composition API, one of the primary unresolved questions is the use of refs vs. reactive objects. It can be cumbersome to use .value everywhere, and it is easy to miss if not using a type system.
Vue Reactivity Transform is a compile-time transform that allows us to write code like this:
<script setup>
let count = $ref(0)
console.log(count)
function increment() {
count++
}
</script>
<template>
{{ count }}
</template>The $ref() method here is a compile-time macro: it is not an actual method that will be called at runtime. Instead, the Vue compiler uses it as a hint to treat the resulting count variable as a reactive variable.
Reactive variables can be accessed and re-assigned just like normal variables, but these operations are compiled into refs with .value. For example, the <script> part of the above component is compiled into:
import { ref } from 'vue'
let count = ref(0)
console.log(count.value)
function increment() {
count.value++
}Every reactivity API that returns refs will have a $-prefixed macro equivalent. These APIs include:
ref->$refcomputed->$computedshallowRef->$shallowRefcustomRef->$customReftoRef->$toRef
These macros are globally available and do not need to be imported when Reactivity Transform is enabled, but you can optionally import them from vue/macros if you want to be more explicit:
import { $ref } from 'vue/macros'
let count = $ref(0)Destructuring with `$()`
It is common for a composition function to return an object of refs, and use destructuring to retrieve these refs. For this purpose, reactivity transform provides the $() macro:
import { useMouse } from '@vueuse/core'
const { x, y } = $(useMouse())
console.log(x, y)Compiled output:
import { toRef } from 'vue'
import { useMouse } from '@vueuse/core'
const __temp = useMouse(),
x = toRef(__temp, 'x'),
y = toRef(__temp, 'y')
console.log(x.value, y.value)Note that if x is already a ref, toRef(__temp, 'x') will simply return it as-is and no additional ref will be created. If a destructured value is not a ref (e.g. a function), it will still work - the value will be wrapped in a ref so the rest of the code works as expected.
$() destructure works on both reactive objects and plain objects containing refs.
Convert Existing Refs to Reactive Variables with `$()`
In some cases we may have wrapped functions that also return refs. However, the Vue compiler won't be able to know ahead of time that a function is going to return a ref. In such cases, the $() macro can also be used to convert any existing refs into reactive variables:
function myCreateRef() {
return ref(0)
}
let count = $(myCreateRef())Reactive Props Destructure
There are two pain points with the current defineProps() usage in <script setup>:
Similar to
.value, you need to always access props asprops.xin order to retain reactivity. This means you cannot destructuredefinePropsbecause the resulting destructured variables are not reactive and will not update.When using the type-only props declaration, there is no easy way to declare default values for the props. We introduced the
withDefaults()API for this exact purpose, but it's still clunky to use.
We can address these issues by applying a compile-time transform when defineProps is used with destructuring, similar to what we saw earlier with $():
<script setup lang="ts">
interface Props {
msg: string
count?: number
foo?: string
}
const {
msg,
// default value just works
count = 1,
// local aliasing also just works
// here we are aliasing `props.foo` to `bar`
foo: bar
} = defineProps()
watchEffect(() => {
// will log whenever the props change
console.log(msg, count, bar)
})
</script>The above will be compiled into the following runtime declaration equivalent:
export default {
props: {
msg: { type: String, required: true },
count: { type: Number, default: 1 },
foo: String
},
setup(props) {
watchEffect(() => {
console.log(props.msg, props.count, props.foo)
})
}
}Retaining Reactivity Across Function Boundaries
While reactive variables relieve us from having to use .value everywhere, it creates an issue of "reactivity loss" when we pass reactive variables across function boundaries. This can happen in two cases:
Passing into function as argument
Given a function that expects a ref as an argument, e.g.:
function trackChange(x: Ref<number>) {
watch(x, (x) => {
console.log('x changed!')
})
}
let count = $ref(0)
trackChange(count) // doesn't work!The above case will not work as expected because it compiles to:
let count = ref(0)
trackChange(count.value)Here count.value is passed as a number, whereas trackChange expects an actual ref. This can be fixed by wrapping count with $$() before passing it:
let count = $ref(0)
- trackChange(count)
+ trackChange($$(count))The above compiles to:
import { ref } from 'vue'
let count = ref(0)
trackChange(count)As we can see, $$() is a macro that serves as an escape hint: reactive variables inside $$() will not get .value appended.
Returning inside function scope
Reactivity can also be lost if reactive variables are used directly in a returned expression:
function useMouse() {
let x = $ref(0)
let y = $ref(0)
// listen to mousemove...
// doesn't work!
return {
x,
y
}
}The above return statement compiles to:
return {
x: x.value,
y: y.value
}In order to retain reactivity, we should be returning the actual refs, not the current value at return time.
Again, we can use $$() to fix this. In this case, $$() can be used directly on the returned object - any reference to reactive variables inside the $$() call will retain the reference to their underlying refs:
function useMouse() {
let x = $ref(0)
let y = $ref(0)
// listen to mousemove...
// fixed
return $$({
x,
y
})
}Using `$$()` on destructured props
$$() works on destructured props since they are reactive variables as well. The compiler will convert it with toRef for efficiency:
const { count } = defineProps<{ count: number }>()
passAsRef($$(count))compiles to:
setup(props) {
const __props_count = toRef(props, 'count')
passAsRef(__props_count)
}TypeScript Integration
Vue provides typings for these macros (available globally) and all types will work as expected. There are no incompatibilities with standard TypeScript semantics, so the syntax will work with all existing tooling.
This also means the macros can work in any files where valid JS / TS are allowed - not just inside Vue SFCs.
Since the macros are available globally, their types need to be explicitly referenced (e.g. in a env.d.ts file):
/// <reference types="vue/macros-global" />When explicitly importing the macros from vue/macros, the type will work without declaring the globals.
Explicit Opt-in
Reactivity Transform is currently disabled by default and requires explicit opt-in. In addition, all of the following setups require vue@^3.2.25.
Vite
- Requires
@vitejs/plugin-vue@^2.0.0 - Applies to SFCs and js(x)/ts(x) files. A fast usage check is performed on files before applying the transform so there should be no performance cost for files not using the macros.
- Note
reactivityTransformis now a plugin root-level option instead of nested asscript.refSugar, since it affects not just SFCs.
// vite.config.js
export default {
plugins: [
vue({
reactivityTransform: true
})
]
}`vue-cli`
- Currently only affects SFCs
- Requires
vue-loader@^17.0.0
// vue.config.js
module.exports = {
chainWebpack: (config) => {
config.module
.rule('vue')
.use('vue-loader')
.tap((options) => {
return {
...options,
reactivityTransform: true
}
})
}
}Plain `webpack` + `vue-loader`
- Currently only affects SFCs
- Requires
vue-loader@^17.0.0
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
reactivityTransform: true
}
}
]
}
}File: src/guide/extras/render-function.md
outline: deep
Render Functions & JSX
Vue recommends using templates to build applications in the vast majority of cases. However, there are situations where we need the full programmatic power of JavaScript. That's where we can use the render function.
If you are new to the concept of virtual DOM and render functions, make sure to read the Rendering Mechanism chapter first.
Basic Usage
Creating Vnodes
Vue provides an h() function for creating vnodes:
import { h } from 'vue'
const vnode = h(
'div', // type
{ id: 'foo', class: 'bar' }, // props
[
/* children */
]
)h() is short for hyperscript - which means "JavaScript that produces HTML (hypertext markup language)". This name is inherited from conventions shared by many virtual DOM implementations. A more descriptive name could be createVnode(), but a shorter name helps when you have to call this function many times in a render function.
The h() function is designed to be very flexible:
// all arguments except the type are optional
h('div')
h('div', { id: 'foo' })
// both attributes and properties can be used in props
// Vue automatically picks the right way to assign it
h('div', { class: 'bar', innerHTML: 'hello' })
// class and style have the same object / array
// value support that they have in templates
h('div', { class: [foo, { bar }], style: { color: 'red' } })
// event listeners should be passed as onXxx
h('div', { onClick: () => {} })
// children can be a string
h('div', { id: 'foo' }, 'hello')
// props can be omitted when there are no props
h('div', 'hello')
h('div', [h('span', 'hello')])
// children array can contain mixed vnodes and strings
h('div', ['hello', h('span', 'hello')])The resulting vnode has the following shape:
const vnode = h('div', { id: 'foo' }, [])
vnode.type // 'div'
vnode.props // { id: 'foo' }
vnode.children // []
vnode.key // null:::warning Note
The full VNode interface contains many other internal properties, but it is strongly recommended to avoid relying on any properties other than the ones listed here. This avoids unintended breakage in case the internal properties are changed.
:::
Declaring Render Functions
When using templates with Composition API, the return value of the setup() hook is used to expose data to the template. When using render functions, however, we can directly return the render function instead:
import { ref, h } from 'vue'
export default {
props: {
/* ... */
},
setup(props) {
const count = ref(1)
// return the render function
return () => h('div', props.msg + count.value)
}
}The render function is declared inside setup() so it naturally has access to the props and any reactive state declared in the same scope.
In addition to returning a single vnode, you can also return strings or arrays:
export default {
setup() {
return () => 'hello world!'
}
}import { h } from 'vue'
export default {
setup() {
// use an array to return multiple root nodes
return () => [
h('div'),
h('div'),
h('div')
]
}
}:::tip
Make sure to return a function instead of directly returning values! The setup() function is called only once per component, while the returned render function will be called multiple times.
:::
We can declare render functions using the render option:
import { h } from 'vue'
export default {
data() {
return {
msg: 'hello'
}
},
render() {
return h('div', this.msg)
}
}The render() function has access to the component instance via this.
In addition to returning a single vnode, you can also return strings or arrays:
export default {
render() {
return 'hello world!'
}
}import { h } from 'vue'
export default {
render() {
// use an array to return multiple root nodes
return [
h('div'),
h('div'),
h('div')
]
}
}If a render function component doesn't need any instance state, they can also be declared directly as a function for brevity:
function Hello() {
return 'hello world!'
}That's right, this is a valid Vue component! See Functional Components for more details on this syntax.
Vnodes Must Be Unique
All vnodes in the component tree must be unique. That means the following render function is invalid:
function render() {
const p = h('p', 'hi')
return h('div', [
// Yikes - duplicate vnodes!
p,
p
])
}If you really want to duplicate the same element/component many times, you can do so with a factory function. For example, the following render function is a perfectly valid way of rendering 20 identical paragraphs:
function render() {
return h(
'div',
Array.from({ length: 20 }).map(() => {
return h('p', 'hi')
})
)
}JSX / TSX
JSX is an XML-like extension to JavaScript that allows us to write code like this:
const vnode = helloInside JSX expressions, use curly braces to embed dynamic values:
const vnode = hello, {userName}create-vue and Vue CLI both have options for scaffolding projects with pre-configured JSX support. If you are configuring JSX manually, please refer to the documentation of @vue/babel-plugin-jsx for details.
Although first introduced by React, JSX actually has no defined runtime semantics and can be compiled into various different outputs. If you have worked with JSX before, do note that Vue JSX transform is different from React's JSX transform, so you can't use React's JSX transform in Vue applications. Some notable differences from React JSX include:
- You can use HTML attributes such as
classandforas props - no need to useclassNameorhtmlFor. - Passing children to components (i.e. slots) works differently.
Vue's type definition also provides type inference for TSX usage. When using TSX, make sure to specify "jsx": "preserve" in tsconfig.json so that TypeScript leaves the JSX syntax intact for Vue JSX transform to process.
Render Function Recipes
Below we will provide some common recipes for implementing template features as their equivalent render functions / JSX.
`v-if`
Template:
yes
noEquivalent render function / JSX:
h('div', [ok.value ? h('div', 'yes') : h('span', 'no')]){ok.value ? yes : no}h('div', [this.ok ? h('div', 'yes') : h('span', 'no')]){this.ok ? yes : no}`v-for`
Template:
<li v-for="{ id, text } in items" :key="id">
{{ text }}
</li>Equivalent render function / JSX:
h(
'ul',
// assuming `items` is a ref with array value
items.value.map(({ id, text }) => {
return h('li', { key: id }, text)
})
){items.value.map(({ id, text }) => {
return <li key={id}>{text}</li>
})}h(
'ul',
this.items.map(({ id, text }) => {
return h('li', { key: id }, text)
})
){this.items.map(({ id, text }) => {
return <li key={id}>{text}</li>
})}`v-on`
Props with names that start with on followed by an uppercase letter are treated as event listeners. For example, onClick is the equivalent of @click in templates.
h(
'button',
{
onClick(event) {
/* ... */
}
},
'click me'
){
/* ... */
}}
>
click meEvent Modifiers
For the .passive, .capture, and .once event modifiers, they can be concatenated after the event name using camelCase.
For example:
h('input', {
onClickCapture() {
/* listener in capture mode */
},
onKeyupOnce() {
/* triggers only once */
},
onMouseoverOnceCapture() {
/* once + capture */
}
}){}}
onKeyupOnce={() => {}}
onMouseoverOnceCapture={() => {}}
/>For other event and key modifiers, the withModifiers helper can be used:
import { withModifiers } from 'vue'
h('div', {
onClick: withModifiers(() => {}, ['self'])
}){}, ['self'])} />Components
To create a vnode for a component, the first argument passed to h() should be the component definition. This means when using render functions, it is unnecessary to register components - you can just use the imported components directly:
import Foo from './Foo.vue'
import Bar from './Bar.jsx'
function render() {
return h('div', [h(Foo), h(Bar)])
}function render() {
return (
<Foo />
)
}As we can see, h can work with components imported from any file format as long as it's a valid Vue component.
Dynamic components are straightforward with render functions:
import Foo from './Foo.vue'
import Bar from './Bar.jsx'
function render() {
return ok.value ? h(Foo) : h(Bar)
}function render() {
return ok.value ? <Foo /> :
}If a component is registered by name and cannot be imported directly (for example, globally registered by a library), it can be programmatically resolved by using the resolveComponent() helper.
Rendering Slots
In render functions, slots can be accessed from the setup() context. Each slot on the slots object is a function that returns an array of vnodes:
export default {
props: ['message'],
setup(props, { slots }) {
return () => [
// default slot:
// <slot />
h('div', slots.default()),
// named slot:
// <slot name="footer" :text="message" />
h(
'div',
slots.footer({
text: props.message
})
)
]
}
}JSX equivalent:
// default
{slots.default()}
// named
{slots.footer({ text: props.message })}In render functions, slots can be accessed from this.$slots:
export default {
props: ['message'],
render() {
return [
// <slot />
h('div', this.$slots.default()),
// <slot name="footer" :text="message" />
h(
'div',
this.$slots.footer({
text: this.message
})
)
]
}
}JSX equivalent:
// <slot />
{this.$slots.default()}
// <slot name="footer" :text="message" />
{this.$slots.footer({ text: this.message })}Passing Slots
Passing children to components works a bit differently from passing children to elements. Instead of an array, we need to pass either a slot function, or an object of slot functions. Slot functions can return anything a normal render function can return - which will always be normalized to arrays of vnodes when accessed in the child component.
// single default slot
h(MyComponent, () => 'hello')
// named slots
// notice the `null` is required to avoid
// the slots object being treated as props
h(MyComponent, null, {
default: () => 'default slot',
foo: () => h('div', 'foo'),
bar: () => [h('span', 'one'), h('span', 'two')]
})JSX equivalent:
// default
<MyComponent>{() => 'hello'}</MyComponent>
// named
<MyComponent>{{
default: () => 'default slot',
foo: () => foo,
bar: () => [one, two]
}}</MyComponent>Passing slots as functions allows them to be invoked lazily by the child component. This leads to the slot's dependencies being tracked by the child instead of the parent, which results in more accurate and efficient updates.
Built-in Components
Built-in components such as <KeepAlive>, , , <Teleport> and <Suspense> must be imported for use in render functions:
import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue'
export default {
setup () {
return () => h(Transition, { mode: 'out-in' }, /* ... */)
}
}import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue'
export default {
render () {
return h(Transition, { mode: 'out-in' }, /* ... */)
}
}`v-model`
The v-model directive is expanded to modelValue and onUpdate:modelValue props during template compilationโwe will have to provide these props ourselves:
export default {
props: ['modelValue'],
emits: ['update:modelValue'],
setup(props, { emit }) {
return () =>
h(SomeComponent, {
modelValue: props.modelValue,
'onUpdate:modelValue': (value) => emit('update:modelValue', value)
})
}
}export default {
props: ['modelValue'],
emits: ['update:modelValue'],
render() {
return h(SomeComponent, {
modelValue: this.modelValue,
'onUpdate:modelValue': (value) => this.$emit('update:modelValue', value)
})
}
}Custom Directives
Custom directives can be applied to a vnode using withDirectives:
import { h, withDirectives } from 'vue'
// a custom directive
const pin = {
mounted() { /* ... */ },
updated() { /* ... */ }
}
//
const vnode = withDirectives(h('div'), [
[pin, 200, 'top', { animate: true }]
])If the directive is registered by name can cannot be imported directly, it can be resolved using the resolveDirective helper.
Functional Components
Functional components are an alternative form of component that don't have any state of their own. They are rendered without creating a component instance, bypassing the usual component lifecycle.
To create a functional component we use a plain function, rather than an options object. The function is effectively the render function for the component.
The signature of a functional component is the same as the setup() hook:
function MyComponent(props, { slots, emit, attrs }) {
// ...
}As there is no this reference for a functional component, Vue will pass in the props as the first argument:
function MyComponent(props, context) {
// ...
}The second argument, context, contains three properties: attrs, emit, and slots. These are equivalent to the instance properties $attrs, $emit, and $slots respectively.
Most of the usual configuration options for components are not available for functional components. However, it is possible to define props and emits by adding them as properties:
MyComponent.props = ['value']
MyComponent.emits = ['click']If the props option is not specified, then the props object passed to the function will contain all attributes, the same as attrs. The prop names will not be normalized to camelCase unless the props option is specified.
Functional components can be registered and consumed just like normal components. If you pass a function as the first argument to h(), it will be treated as a functional component.
File: src/guide/extras/rendering-mechanism.md
outline: deep
Rendering Mechanism
How does Vue take a template and turn it into actual DOM nodes? How does Vue update those DOM nodes efficiently? We will attempt to shed some light on these questions here by diving into Vue's internal rendering mechanism.
Virtual DOM
You have probably heard about the term virtual DOM, which Vue's rendering system is based upon.
The virtual DOM (VDOM) is a programming concept where an ideal, or โvirtualโ, representation of a UI is kept in memory and synced with the โrealโ DOM. The concept was pioneered by React, and has been adapted in many other frameworks with different implementations, including Vue.
Virtual DOM is more of a pattern than a specific technology, so there is no one canonical implementation. We can illustrate the idea using a simple example:
const vnode = {
type: 'div',
props: {
id: 'hello'
},
children: [
/* more vnodes */
]
}Here, vnode is a plain JavaScript object (a "virtual node") representing a `` element. It contains all the information that we need to create the actual element. It also contains more children vnodes, which makes it the root of a virtual DOM tree.
A runtime renderer can walk a virtual DOM tree and construct a real DOM tree from it. This process is called mount.
If we have two copies of virtual DOM trees, the renderer can also walk and compare the two trees, figuring out the differences, and apply those changes to the actual DOM. This process is called patch, also known as "diffing" or "reconciliation".
The main benefit of virtual DOM is that it gives the developer the ability to programmatically create, inspect and compose desired UI structures in a declarative way, while leaving the direct DOM manipulation to the renderer.
Render Pipeline
At the high level, this is what happens when a Vue component is mounted:
Compile: Vue templates are compiled into render functions: functions that return virtual DOM trees. This step can be done either ahead-of-time via a build step, or on-the-fly by using the runtime compiler.
Mount: The runtime renderer invokes the render functions, walks the returned virtual DOM tree, and creates actual DOM nodes based on it. This step is performed as a reactive effect, so it keeps track of all reactive dependencies that were used.
Patch: When a dependency used during mount changes, the effect re-runs. This time, a new, updated Virtual DOM tree is created. The runtime renderer walks the new tree, compares it with the old one, and applies necessary updates to the actual DOM.
Templates vs. Render Functions
Vue templates are compiled into virtual DOM render functions. Vue also provides APIs that allow us to skip the template compilation step and directly author render functions. Render functions are more flexible than templates when dealing with highly dynamic logic, because you can work with vnodes using the full power of JavaScript.
So why does Vue recommend templates by default? There are a number of reasons:
Templates are closer to actual HTML. This makes it easier to reuse existing HTML snippets, apply a11y best practices, style with CSS, and for designers to understand and modify.
Templates are easier to statically analyze due to their more deterministic syntax. This allows Vue's template compiler to apply many compile-time optimizations to improve the performance of the virtual DOM (which we will discuss below).
In practice, templates are sufficient for most use cases in applications. Render functions are typically only used in reusable components that need to deal with highly dynamic rendering logic. Render function usage is discussed in more detail in Render Functions & JSX.
Compiler-Informed Virtual DOM
The virtual DOM implementation in React and most other virtual-DOM implementations are purely runtime: the reconciliation algorithm cannot make any assumptions about the incoming virtual DOM tree, so it has to fully traverse the tree and diff the props of every vnode in order to ensure correctness. In addition, even if a part of the tree never changes, new vnodes are always created for them on each re-render, resulting in unnecessary memory pressure. This is one of the most criticized aspect of virtual DOM: the somewhat brute-force reconciliation process sacrifices efficiency in return for declarativeness and correctness.
But it doesn't have to be that way. In Vue, the framework controls both the compiler and the runtime. This allows us to implement many compile-time optimizations that only a tightly-coupled renderer can take advantage of. The compiler can statically analyze the template and leave hints in the generated code so that the runtime can take shortcuts whenever possible. At the same time, we still preserve the capability for the user to drop down to the render function layer for more direct control in edge cases. We call this hybrid approach Compiler-Informed Virtual DOM.
Below, we will discuss a few major optimizations done by the Vue template compiler to improve the virtual DOM's runtime performance.
Static Hoisting
Quite often there will be parts in a template that do not contain any dynamic bindings:
foo
bar
{{ dynamic }}The foo and bar divs are static - re-creating vnodes and diffing them on each re-render is unnecessary. The Vue compiler automatically hoists their vnode creation calls out of the render function, and reuses the same vnodes on every render. The renderer is also able to completely skip diffing them when it notices the old vnode and the new vnode are the same one.
In addition, when there are enough consecutive static elements, they will be condensed into a single "static vnode" that contains the plain HTML string for all these nodes (Example). These static vnodes are mounted by directly setting innerHTML. They also cache their corresponding DOM nodes on initial mount - if the same piece of content is reused elsewhere in the app, new DOM nodes are created using native cloneNode(), which is extremely efficient.
Patch Flags
For a single element with dynamic bindings, we can also infer a lot of information from it at compile time:
{{ dynamic }}When generating the render function code for these elements, Vue encodes the type of update each of them needs directly in the vnode creation call:
createElementVNode("div", {
class: _normalizeClass({ active: _ctx.active })
}, null, 2 /* CLASS */)The last argument, 2, is a patch flag. An element can have multiple patch flags, which will be merged into a single number. The runtime renderer can then check against the flags using bitwise operations to determine whether it needs to do certain work:
if (vnode.patchFlag & PatchFlags.CLASS /* 2 */) {
// update the element's class
}Bitwise checks are extremely fast. With the patch flags, Vue is able to do the least amount of work necessary when updating elements with dynamic bindings.
Vue also encodes the type of children a vnode has. For example, a template that has multiple root nodes is represented as a fragment. In most cases, we know for sure that the order of these root nodes will never change, so this information can also be provided to the runtime as a patch flag:
export function render() {
return (_openBlock(), _createElementBlock(_Fragment, null, [
/* children */
], 64 /* STABLE_FRAGMENT */))
}The runtime can thus completely skip child-order reconciliation for the root fragment.
Tree Flattening
Taking another look at the generated code from the previous example, you'll notice the root of the returned virtual DOM tree is created using a special createElementBlock() call:
export function render() {
return (_openBlock(), _createElementBlock(_Fragment, null, [
/* children */
], 64 /* STABLE_FRAGMENT */))
}Conceptually, a "block" is a part of the template that has stable inner structure. In this case, the entire template has a single block because it does not contain any structural directives like v-if and v-for.
Each block tracks any descendent nodes (not just direct children) that have patch flags. For example:
...
{{ bar }}The result is a flattened array that contains only the dynamic descendent nodes:
div (block root)
- div with :id binding
- div with {{ bar }} bindingWhen this component needs to re-render, it only needs to traverse the flattened tree instead of the full tree. This is called Tree Flattening, and it greatly reduces the number of nodes that need to be traversed during virtual DOM reconciliation. Any static parts of the template are effectively skipped.
v-if and v-for directives will create new block nodes:
...A child block is tracked inside the parent block's array of dynamic descendents. This retains a stable structure for the parent block.
Impact on SSR Hydration
Both patch flags and tree flattening also greatly improve Vue's SSR Hydration performance:
Single element hydration can take fast paths based on the corresponding vnode's patch flag.
Only block nodes and their dynamic descendents need to be traversed during hydration, effectively achieving partial hydration at the template level.
File: src/guide/extras/ways-of-using-vue.md
Ways of Using Vue
We believe there is no "one size fits all" story for the web. This is why Vue is designed to be flexible and incrementally adoptable. Depending on your use case, Vue can be used in different ways to strike the optimal balance between stack complexity, developer experience and end performance.
Standalone Script
Vue can be used as a standalone script file - no build step required! If you have a backend framework already rendering most of the HTML, or your frontend logic isn't complex enough to justify a build step, this is the easiest way to integrate Vue into your stack. You can think of Vue as a more declarative replacement of jQuery in such cases.
Vue also provides an alternative distribution called petite-vue that is specifically optimized for progressively enhancing existing HTML. It has a smaller feature set, but is extremely lightweight and uses an implementation that is more efficient in no-build-step scenarios.
Embedded Web Components
You can use Vue to build standard Web Components that can be embedded in any HTML page, regardless of how they are rendered. This option allows you to leverage Vue in a completely consumer-agnostic fashion: the resulting web components can be embedded in legacy applications, static HTML, or even applications built with other frameworks.
Single-Page Application (SPA)
Some applications require rich interactivity and non-trivial stateful logic on the frontend. The best way to build such applications is to use an architecture where Vue not only controls the entire page, but also handles data updates and navigations without having to reload the page. This type of application is typically referred to as a Single-Page Application (SPA).
Vue provides core libraries and comprehensive tooling support with amazing developer experience for building modern SPAs, including:
- Client-side router
- Blazing fast build tool chain
- IDE support
- Browser devtools
- TypeScript integrations
- Testing utilities
SPAs typically require the backend to expose API endpoints - but you can also pair Vue with solutions like Inertia.js to get the SPA benefits while retaining a server-centric development model.
Fullstack / SSR
Pure client-side SPAs are problematic when the app is sensitive to SEO and time-to-content. This is because the browser will receive a largely empty HTML page, and has to wait until the JavaScript is loaded before rendering anything.
Vue provides first-class APIs to "render" a Vue app into HTML strings on the server. This allows the server to send back already-rendered HTML, allowing end users to see the content immediately while the JavaScript is being downloaded. Vue will then "hydrate" the application on the client side to make it interactive. This is called Server-Side Rendering (SSR) and it greatly improves Core Web Vital metrics such as Largest Contentful Paint (LCP).
There are higher-level Vue-based frameworks built on top of this paradigm, such as Nuxt, which allow you to develop a fullstack application using Vue and JavaScript.
JAMStack / SSG
Server-side rendering can be done ahead of time if the required data is static. This means we can pre-render an entire application into HTML and serve them as static files. This improves site performance and makes deployment a lot simpler since we no longer need to dynamically render pages on each request. Vue can still hydrate such applications to provide rich interactivity on the client. This technique is commonly referred to as Static-Site Generation (SSG), also known as JAMStack.
The Vue team maintains a static-site generator called VitePress, which powers this website you are reading right now! In addition, Nuxt also supports SSG. You can even mix SSR and SSG for different routes in the same Nuxt app.
Beyond the Web
Although Vue is primarily designed for building web applications, it is by no means limited to just the browser. You can:
- Build desktop apps with Electron or Tauri
- Build mobile apps with Ionic Vue
- Build desktop and mobile apps from the same codebase with Quasar
- Use Vue's Custom Renderer API to build custom renderers targeting WebGL or even the terminal!
File: src/guide/extras/web-components.md
Vue and Web Components
Web Components is an umbrella term for a set of web native APIs that allows developers to create reusable custom elements.
We consider Vue and Web Components to be primarily complementary technologies. Vue has excellent support for both consuming and creating custom elements. Whether you are integrating custom elements into an existing Vue application, or using Vue to build and distribute custom elements, you are in good company.
Using Custom Elements in Vue
Vue scores a perfect 100% in the Custom Elements Everywhere tests. Consuming custom elements inside a Vue application largely works the same as using native HTML elements, with a few things to keep in mind:
Skipping Component Resolution
By default, Vue will attempt to resolve a non-native HTML tag as a registered Vue component before falling back to rendering it as a custom element. This will cause Vue to emit a "failed to resolve component" warning during development. To let Vue know that certain elements should be treated as custom elements and skip component resolution, we can specify the compilerOptions.isCustomElement option.
If you are using Vue with a build setup, the option should be passed via build configs since it is a compile-time option.
Example In-Browser Config
// Only works if using in-browser compilation.
// If using build tools, see config examples below.
app.config.compilerOptions.isCustomElement = (tag) => tag.includes('-')Example Vite Config
// vite.config.js
import vue from '@vitejs/plugin-vue'
export default {
plugins: [
vue({
template: {
compilerOptions: {
// treat all tags with a dash as custom elements
isCustomElement: (tag) => tag.includes('-')
}
}
})
]
}Example Vue CLI Config
// vue.config.js
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => ({
...options
compilerOptions: {
// treat any tag that starts with ion- as custom elements
isCustomElement: tag => tag.startsWith('ion-')
}
}))
}
}Passing DOM Properties
Since DOM attributes can only be strings, we need to pass complex data to custom elements as DOM properties. When setting props on a custom element, Vue 3 automatically checks DOM-property presence using the in operator and will prefer setting the value as a DOM property if the key is present. This means that, in most cases, you won't need to think about this if the custom element follows the recommended best practices.
However, there could be rare cases where the data must be passed as a DOM property, but the custom element does not properly define/reflect the property (causing the in check to fail). In this case, you can force a v-bind binding to be set as a DOM property using the .prop modifier:
<my-element :user.prop="{ name: 'jack' }"></my-element>
<my-element .user="{ name: 'jack' }"></my-element>Building Custom Elements with Vue
The primary benefit of custom elements is that they can be used with any framework, or even without a framework. This makes them ideal for distributing components where the end consumer may not be using the same frontend stack, or when you want to insulate the end application from the implementation details of the components it uses.
defineCustomElement
Vue supports creating custom elements using exactly the same Vue component APIs via the defineCustomElment method. The method accepts the same argument as defineComponent, but instead returns a custom element constructor that extends HTMLElement:
<my-vue-element></my-vue-element>import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
// normal Vue component options here
props: {},
emits: {},
template: `...`,
// defineCustomElement only: CSS to be injected into shadow root
styles: [`/* inlined css */`]
})
// Register the custom element.
// After registration, all `<my-vue-element>` tags
// on the page will be upgraded.
customElements.define('my-vue-element', MyVueElement)
// You can also programmatically instantiate the element:
// (can only be done after registration)
document.body.appendChild(
new MyVueElement({
// initial props (optional)
})
)Lifecycle
A Vue custom element will mount an internal Vue component instance inside its shadow root when the element's
connectedCallbackis called for the first time.When the element's
disconnectedCallbackis invoked, Vue will check whether the element is detached from the document after a microtask tick.If the element is still in the document, it's a move and the component instance will be perserved;
If the element is detached from the document, it's a removal and the component instance will be unmounted.
Props
All props declared using the
propsoption will be defined on the custom element as properties. Vue will automatically handle the reflection between attributes / properties where appropriate.Attributes are always reflected to corresponding properties.
Properties with primitive values (
string,booleanornumber) are reflected as attributes.
Vue also automatically casts props declared with
BooleanorNumbertypes into the desired type when they are set as attributes (which are always strings). For example given the following props declaration:jsprops: { selected: Boolean, index: Number }And the custom element usage:
vue-html<my-element selected index="1"></my-element>In the component,
selectedwill be cast totrue(boolean) andindexwill be cast to1(number).
Events
Events emitted via this.$emit or setup emit are dispatched as native CustomEvents on the custom element. Additional event arguments (payload) will be exposed as an array on the CustomEvent object as its details property.
Slots
Inside the component, slots can be rendered using the <slot/> element as usual. However, when consuming the resulting element, it only accepts native slots syntax:
Scoped slots are not supported.
When passing named slots, use the
slotattribute instead of thev-slotdirective:vue-html<my-element> hello </my-element>
Provide / Inject
The Provide / Inject API and its Composition API equivalent also work between Vue-defined custom elements. However, note that this works only between custom elements. i.e. a Vue-defined custom element won't be able to inject properties provided by a non-custom-element Vue component.
SFC as Custom Element
defineCustomElement also works with Vue Single-File Components (SFCs). However, with the default tooling setup, the <style> inside the SFCs will still be extracted and merged into a single CSS file during production build. When using an SFC as a custom element, it is often desirable to inject the <style> tags into the custom element's shadow root instead.
The official SFC toolings support importing SFCs in "custom element mode" (requires @vitejs/plugin-vue@^1.4.0 or vue-loader@^16.5.0). An SFC loaded in custom element mode inlines its <style> tags as strings of CSS and exposes them under the component's styles option. This will be picked up by defineCustomElement and injected into the element's shadow root when instantiated.
To opt-in to this mode, simply end your component file name with .ce.vue:
import { defineCustomElement } from 'vue'
import Example from './Example.ce.vue'
console.log(Example.styles) // ["/* inlined css */"]
// convert into custom element constructor
const ExampleElement = defineCustomElement(Example)
// register
customElements.define('my-example', ExampleElement)If you wish to customize what files should be imported in custom element mode (for example treating all SFCs as custom elements), you can pass the customElement option to the respective build plugins:
Tips for a Vue Custom Elements Library
When building custom elements with Vue, the elements will rely on Vue's runtime. There is a ~16kb baseline size cost depending on how many features are being used. This means it is not ideal to use Vue if you are shipping a single custom element - you may want to use vanilla JavaScript, petite-vue, or frameworks that specialize in small runtime size. However, the base size is more than justifiable if you are shipping a collection of custom elements with complex logic, as Vue will allow each component to be authored with much less code. The more elements you are shipping together, the better the trade-off.
If the custom elements will be used in an application that is also using Vue, you can choose to externalize Vue from the built bundle so that the elements will be using the same copy of Vue from the host application.
It is recommended to export the individual element constructors to give your users the flexibility to import them on-demand and register them with desired tag names. You can also export a convenience function to automatically register all elements. Here's an example entry point of a Vue custom element library:
import { defineCustomElement } from 'vue'
import Foo from './MyFoo.ce.vue'
import Bar from './MyBar.ce.bar'
const MyFoo = defineCustomElement(Foo)
const MyBar = defineCustomElement(Bar)
// export individual elements
export { MyFoo, MyBar }
export function register() {
customElements.define('my-foo', MyFoo)
customElements.define('my-bar', MyBar)
}If you have many components, you can also leverage build tool features such as Vite's glob import or webpack's require.context to load all components from a directory.
Web Components vs. Vue Components
Some developers believe that framework-proprietary component models should be avoided, and that exclusively using Custom Elements makes an application "future-proof". Here we will try to explain why we believe that this is an overly simplistic take on the problem.
There is indeed a certain level of feature overlap between Custom Elements and Vue Components: they both allow us to define reusable components with data passing, event emitting, and lifecycle management. However, Web Components APIs are relatively low-level and bare-bones. To build an actual application, we need quite a few additional capabilities which the platform does not cover:
A declarative and efficient templating system;
A reactive state management system that facilitates cross-component logic extraction and reuse;
A performant way to render the components on the server and hydrate them on the client (SSR), which is important for SEO and Web Vitals metrics such as LCP. Native custom elements SSR typically involves simulating the DOM in Node.js and then serializing the mutated DOM, while Vue SSR compiles into string concatenation whenever possible, which is much more efficient.
Vue's component model is designed with these needs in mind as a coherent system.
With a competent engineering team, you could probably build the equivalent on top of native Custom Elements - but this also means you are taking on the long-term maintenance burden of an in-house framework, while losing out on the ecosystem and community benefits of a mature framework like Vue.
There are also frameworks built using Custom Elements as the basis of their component model, but they all inevitably have to introduce their proprietary solutions to the problems listed above. Using these frameworks entails buying into their technical decisions on how to solve these problems - which, despite what may be advertised, doesn't automatically insulate you from potential future churns.
There are also some areas where we find custom elements to be limiting:
Eager slot evaluation hinders component composition. Vue's scoped slots are a powerful mechanism for component composition, which can't be supported by custom elements due to native slots' eager nature. Eager slots also mean the receiving component cannot control when or whether to render a piece of slot content.
Shipping custom elements with shadow DOM scoped CSS today requires embedding the CSS inside JavaScript so that they can be injected into shadow roots at runtime. They also result in duplicated styles in markup in SSR scenarios. There are platform features being worked on in this area - but as of now they are not yet universally supported, and there are still production performance / SSR concerns to be addressed. In the meanwhile, Vue SFCs provide CSS scoping mechanisms that support extracting the styles into plain CSS files.
Vue will always be staying up to date with the latest standards in the web platform, and we will happily leverage whatever the platform provides if it makes our job easier. However, our goal is to provide solutions that work well and work today. That means we have to incorporate new platform features with a critical mindset - and that involves filling the gaps where the standards fall short while that is still the case.