Vue and Browser Utilities
Interactive example
Change the element's color and dimensions to inspect classes, queries, and styles. You can also start or stop a Vue scope, convert the sample PNG, download a sample file, or open print preview.
View example source
tsx
import { useI18n, useSiderScroll } from '@/hooks'
import {
arrayBufferToBase64Image,
autoPrefixStyle,
call,
colorToRgba,
completeSize,
downloadAnyFile,
downloadBase64File,
effectDispose,
fileToBase64,
hasClass,
positionSelectedMenuItem,
printDom,
queryElements,
removeClass,
removeStyle,
renderNode,
setClass,
setStyle,
unrefElement,
watchEffectWithTarget,
} from '@/utils'
import { NButton, NCard, NFlex, NInput, NSwitch } from 'naive-ui'
import { effectScope } from 'vue'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'
const png =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j9x0AAAAASUVORK5CYII='
export default defineComponent({
name: 'DocsBrowserUtils',
setup() {
const { t } = useI18n('docsExamples')
const text = (key: string) => t<string>(key)
const target = ref<HTMLElement>()
const result = ref('')
const color = ref('#3b63d9')
const size = ref('150')
const zero = ref(true)
const log = ref<string[]>([])
const count = ref(0)
const observed = ref<number>()
const cleaned = ref(false)
const running = ref(false)
const dataUrl = ref('')
const fileResult = ref('')
const scrollSidebar = useSiderScroll()
let scope: ReturnType<typeof effectScope> | undefined
const change = (apply: boolean) => {
const node = unrefElement(target)
if (!node) return
const actionScope = effectScope()
actionScope.run(() => {
if (apply) {
setClass(node, 'docs-utility-marked')
setStyle(node, {
color: colorToRgba(color.value, 1, '#3b63d9'),
width: completeSize(size.value),
})
} else {
removeClass(node, 'docs-utility-marked')
removeStyle(node, ['color', 'width'])
}
result.value = JSON.stringify(
{
hasClass: hasClass(node, 'docs-utility-marked').value,
matched: queryElements('attr:data-docs-utility')?.length,
style: node.getAttribute('style'),
prefixes: autoPrefixStyle('transform'),
},
null,
2,
)
})
actionScope.stop()
}
const start = () => {
if (running.value) return
scope = effectScope()
cleaned.value = false
running.value = true
scope.run(() => {
watchEffectWithTarget(() => {
observed.value = count.value
})
effectDispose(() => {
cleaned.value = true
running.value = false
})
})
}
const stop = () => scope?.stop()
onScopeDispose(stop)
const convert = async () => {
try {
const bytes = Uint8Array.from(atob(png), (char) => char.charCodeAt(0))
dataUrl.value = arrayBufferToBase64Image(bytes.buffer)
const data = await fileToBase64(
new File([bytes], 'ray-example.png', { type: 'image/png' }),
)
fileResult.value =
data === dataUrl.value ? text('browser.matchingDataUrl') : data
} catch (error) {
fileResult.value = String(error)
}
}
return () => (
<DemoPage
title={text('browser.title')}
description={text('browser.intro')}
>
<div class="r-demo-grid">
<NCard title={text('browser.dom')}>
<NFlex>
<NInput
v-model:value={color.value}
aria-label={text('browser.color')}
/>
<NInput
v-model:value={size.value}
aria-label={text('browser.width')}
/>
<NButton onClick={() => change(true)}>
{text('browser.apply')}
</NButton>
<NButton onClick={() => change(false)}>
{text('browser.remove')}
</NButton>
</NFlex>
<p ref={target} data-docs-utility="">
{text('browser.target')}
</p>
<DemoResult label={text('browser.domResult')}>
<pre>{result.value}</pre>
</DemoResult>
<NFlex>
<NButton onClick={() => scrollSidebar(0, 0)}>
{text('browser.sidebarTop')}
</NButton>
<NButton onClick={positionSelectedMenuItem}>
{text('browser.locateMenu')}
</NButton>
</NFlex>
</NCard>
<NCard title={text('browser.vue')}>
<NFlex align="center">
<NSwitch
v-model:value={zero.value}
aria-label={text('browser.renderZero')}
/>
<span>
{renderNode(zero.value ? 0 : null, {
defaultElement: text('browser.fallback'),
})()}
</span>
<NButton
onClick={() => {
log.value = []
call(
[
(n: number) => log.value.push(`A:${n}`),
(n: number) => log.value.push(`B:${n}`),
],
count.value,
)
}}
>
{text('browser.callBoth')}
</NButton>
</NFlex>
<NFlex>
<NButton disabled={running.value} onClick={start}>
{text('browser.start')}
</NButton>
<NButton onClick={() => count.value++}>
{text('browser.increment')}
</NButton>
<NButton disabled={!running.value} onClick={stop}>
{text('browser.stop')}
</NButton>
</NFlex>
<DemoResult label={text('browser.vueResult')}>
<code>
{JSON.stringify({
count: count.value,
observed: observed.value,
cleaned: cleaned.value,
calls: log.value,
})}
</code>
</DemoResult>
</NCard>
<NCard title={text('browser.files')}>
<NFlex>
<NButton onClick={convert}>{text('browser.convert')}</NButton>
<NButton
disabled={!dataUrl.value}
onClick={() =>
downloadBase64File(dataUrl.value, 'ray-example.png')
}
>
{text('browser.downloadPng')}
</NButton>
<NButton
onClick={() =>
downloadAnyFile(
new Blob(['Ray Template\n'], { type: 'text/plain' }),
'ray-example.txt',
)
}
>
{text('browser.downloadBlob')}
</NButton>
<NButton
onClick={async () => {
fileResult.value = String(await printDom(target))
}}
>
{text('browser.print')}
</NButton>
</NFlex>
<DemoResult label={text('browser.fileResult')}>
{fileResult.value}
</DemoResult>
</NCard>
</div>
</DemoPage>
)
},
})Resolve Vue targets
BasicTarget<T> can be an element, component instance, ref, getter, or empty value. unrefElement(target, fallback?) unwraps it at call time and prefers $el for components. A multi-root component's $el may be unsuitable for DOM operations. Bind a native element ref for capture, fullscreen, or styling.
| Utility | Behavior |
|---|---|
call(fnOrFns, ...args) | Calls one function or an array in order, forwarding the arguments. |
renderNode(value, { defaultElement }?) | Normalizes to a render function. Only null and undefined use the fallback. 0 and empty strings are preserved. |
effectDispose(cleanup) | Registers cleanup and returns true in an active effect scope. Otherwise returns false and the caller owns cleanup. |
watchEffectWithTarget(effect, options?) | Compatibility entry point for Vue watchEffect. Returns a stop handle and stops with its active scope. |
DOM, styling, and sizing
| API | Behavior |
|---|---|
setClass(target, names) / removeClass(target, names) | Applies to the current and replacement targets. Accepts whitespace-separated names or an array. removeAllClass clears all classes. |
hasClass(target, names) | Reactive Boolean, true if any complete class name matches. Tracks target changes. An external class edit does not trigger recalculation. |
setStyle(target, styles) | Accepts an object, declaration string, or array of strings and preserves other inline styles. Supports camelCase, custom properties, and !important. |
removeStyle(target, names) | Removes inline styles by their CSS or camelCase names. |
autoPrefixStyle(name) | Returns a compatibility map of the original property and legacy prefixed names without touching the DOM. |
completeSize(value, unit = 'px') | Adds units to numbers and numeric strings. Keeps percentages, CSS keywords, and expressions. |
colorToRgba(color, alpha = 1, fallback?) | Supports comma-separated RGB and HSL and common Hex values. Hex with alpha retains it. Unknown formats use the given fallback or the original string. |
queryElements(selector, { defaultElement }?) | Returns DOM elements. attr:data-id is equivalent to an attribute selector. No matches return an empty array. An empty or invalid selector with no fallback returns null. |
positionSelectedMenuItem() | Scrolls a rendered active menu item into view if needed. Expand its ancestors and wait for the DOM first. |
Class and style functions observe target changes. Create them in component setup or an effect scope. With SSR, call APIs that read document or window after mounting.
Files, downloads, and printing
| API | Behavior |
|---|---|
fileToBase64(file) | Promise of a Data URL with MIME type. Read failure or abort rejects. |
arrayBufferToBase64Image(buffer) | Adds a PNG Data URL prefix to PNG bytes. It does not convert other formats. |
downloadBase64File(url, fileName) | Starts download through a temporary link, then cleans up. |
downloadAnyFile(data, fileName) | Accepts Data URL, Blob, File, or ArrayBuffer. Binary data uses a temporary object URL. The promise resolves once the download is initiated. |
printDom(target, { printOptions?, domToImageOptions? }) | Captures the DOM as JPEG, then opens print preview. Returns Promise<boolean>, logs failures and returns false, and updates the global Loading Bar if available. |
ts
import { downloadAnyFile, fileToBase64 } from '@/utils'
export const previewFile = (file: File) => fileToBase64(file)
export const downloadReport = (pdf: Blob) => downloadAnyFile(pdf, 'report.pdf')DOM utilities · File utilities · Vue utilities · Capture and print hooks