Marking components as Cachable #16221
Replies: 1 comment
|
Vue already optimizes most of this case at compile time. Given a component containing only static markup: <!-- StaticNotice.vue -->
<template>
<aside class="notice">
<h2>Scheduled maintenance</h2>
<p>The service will be unavailable from 02:00 to 03:00 UTC.</p>
</aside>
</template>Vue’s template compiler identifies the static subtree and hoists it out of the render function. The resulting VNode can be reused, future patching is skipped, and sufficiently large groups of static elements can be compiled into a static VNode backed by an HTML string. That optimization avoids repeatedly creating and diffing the static subtree. A normal SFC still has a component boundary, though, so Vue must perform the component mount and unmount work whenever a new instance is introduced. For content that is conditionally shown many times, keeping the component mounted may solve the underlying issue: <script setup lang="ts">
import { ref } from 'vue'
import StaticNotice from './StaticNotice.vue'
const visible = ref(false)
</script>
<template>
<button @click="visible = !visible">
Toggle notice
</button>
<!-- The DOM is created once and display is toggled -->
<StaticNotice v-show="visible" />
</template>With <StaticNotice v-if="visible" />With For switching between dynamic components, <script setup lang="ts">
import { shallowRef } from 'vue'
import StaticNotice from './StaticNotice.vue'
import OtherView from './OtherView.vue'
const activeView = shallowRef(StaticNotice)
</script>
<template>
<KeepAlive>
<component :is="activeView" />
</KeepAlive>
</template>A functional component is also available when no component state or lifecycle is required: // StaticNotice.ts
import { h, type FunctionalComponent } from 'vue'
export const StaticNotice: FunctionalComponent = () =>
h('aside', { class: 'notice' }, [
h('h2', 'Scheduled maintenance'),
h(
'p',
'The service will be unavailable from 02:00 to 03:00 UTC.'
)
])
StaticNotice.inheritAttrs = falseFunctional components are rendered as functions without state or the usual component lifecycle hooks. They still produce VNodes and DOM when mounted, so they do not eliminate the mounting operation entirely.
<template>
<aside v-once>
<h2>{{ title }}</h2>
<p>{{ message }}</p>
</aside>
</template>For completely static markup, A separate “cacheable component” type may therefore overlap with static hoisting, functional components, References
|
Uh oh!
There was an error while loading. Please reload this page.
I'm thinking in order to improve performance, can we have support for a new component type that takes no props and only renders html and is cachable? So vue doesn't have to pass through the mount process everytime for it? I can create an issue if this makes sense and explain more as well
All reactions