feat(demos): add working examples with visible results

This commit is contained in:
XiaoDaiGua-Ray 2026-11-04 10:29:51 +08:00
parent 15e4c3d427
commit dfa9fdbec2
40 changed files with 2425 additions and 1593 deletions

View File

@ -0,0 +1,18 @@
import { RIframe } from '@/components/RIframe'
import { mount } from '@vue/test-utils'
describe('RIframe loading strategy', () => {
it.each([
[true, 'lazy'],
[false, 'eager'],
['eager', 'eager'],
] as const)('sets loading=%s to %s', (lazy, expected) => {
const wrapper = mount(RIframe, { props: { lazy, src: '/embed.html' } })
try {
expect(wrapper.get('iframe').attributes('loading')).toBe(expected)
} finally {
wrapper.unmount()
}
})
})

View File

@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Ray Template embed</title>
<style>
:root { color-scheme: light dark; }
body {
display: grid;
min-height: 100vh;
margin: 0;
place-items: center;
background: #182436;
color: #d5f367;
font: 600 14px system-ui, sans-serif;
}
main { display: grid; gap: 8px; justify-items: center; }
img { width: 72px; height: 72px; }
</style>
<main>
<img src="../ray.svg" alt="" />
<span>Ray Template</span>
</main>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,8 @@
{
"ticket": { "id": "RAY-024", "title": "Review the workspace", "status": "ready" },
"cities": {
"Hangzhou": { "temperature": 19, "humidity": 66 },
"Shanghai": { "temperature": 17, "humidity": 73 },
"Chengdu": { "temperature": 21, "humidity": 58 }
}
}

View File

@ -1,37 +1,20 @@
import { request } from '@/axios'
import type { BasicResponse } from '@/types'
interface AxiosTestResponse extends GlobalRecordable {
data: GlobalRecordable[]
city?: string
interface RequestFixture {
ticket: { id: string; title: string; status: string }
cities: Record<string, { temperature: number; humidity: number }>
}
interface JSONPlaceholder {
completed: boolean
id: number
title: string
userId: number
}
export const requestFixtureUrl = `${import.meta.env.BASE_URL}examples/request.json`
/**
*
* @param city 天气查询接口所需的城市名称
*
* @description
* 按城市名称请求演示天气接口。
*
* @returns 演示接口的响应 Promise
*/
export const getWeather = (city: string) => {
return request<AxiosTestResponse>({
url: `https://www.tianqiapi.com/api?version=v9&appid=23035354&appsecret=8YvlPNrz&city=${city}`,
method: 'get',
})
}
export const getRequestFixture = () =>
request<RequestFixture>({ url: requestFixtureUrl, method: 'get' })
export const getTypicCode = () => {
return request<JSONPlaceholder>({
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'get',
})
export const getWeather = async (city: string) => {
const { cities } = await getRequestFixture()
const weather = cities[city]
if (!weather) throw new Error('Missing sample city.')
return { city, ...weather }
}

View File

@ -4,7 +4,6 @@ import { call, completeSize } from '@/utils'
import LogicFlow from '@logicflow/core'
import { omit } from 'lodash-es'
import { useTemplateRef } from 'vue'
import type { WatchStopHandle } from 'vue'
import props from './props'
import type { FlowGraphData, G } from './types'
@ -35,16 +34,11 @@ export default defineComponent({
edgeTextEdit: false,
textEdit: false,
}
// watchData 回调
let watchDataStop: WatchStopHandle
// 默认流程图数据
const defaultGraphData = {
nodes: [],
edges: [],
}
const cacheProps = {
readonly: props.readonly,
}
// 注册流程图插件
const registerExtension = () => {
@ -73,6 +67,7 @@ export default defineComponent({
// 单独处理 isSilentMode 配置项
Object.assign(readonlyOptions, ops, {
isSilentMode: bool,
adjustNodePosition: !bool,
})
logicFlowInstRef.value.updateEditConfig(readonlyOptions)
}
@ -107,31 +102,17 @@ export default defineComponent({
updateFlowConfig(readonly)
}
watchEffect(() => {
if (props.watchData) {
watchDataStop = watch(
() => props.data,
(ndata) => {
if (logicFlowInstRef.value) {
ndata && logicFlowInstRef.value.renderRawData(ndata as G)
} else {
setupFlowRender(ndata)
}
},
)
} else {
watchDataStop?.()
}
if (props.readonly !== cacheProps.readonly) {
updateFlowConfig(props.readonly)
cacheProps.readonly = props.readonly
}
})
watch(
() => props.data,
(data) => {
if (props.watchData && data)
logicFlowInstRef.value?.renderRawData(data as G)
},
)
watch(() => props.readonly, updateFlowConfig)
onMounted(() => {
setupFlowRender()
setupFlowRender(props.data)
const { onRegister } = props
@ -140,6 +121,8 @@ export default defineComponent({
}
})
onBeforeUnmount(() => logicFlowInstRef.value?.destroy())
return {
flowDomRef,
cssVars,

View File

@ -68,7 +68,13 @@ export default defineComponent({
allow={this.allow}
name={this.name}
title={this.title}
loading={typeof this.lazy === 'boolean' ? 'lazy' : this.lazy}
loading={
this.lazy === true
? 'lazy'
: this.lazy === false
? 'eager'
: this.lazy
}
/>
),
}}

View File

@ -5,12 +5,15 @@ import type {
MaybeElement,
MaybeElementRef,
OnClickOutsideHandler,
OnClickOutsideOptions,
} from '@vueuse/core'
import type { MaybeRefOrGetter } from 'vue'
export interface UseContextmenuCoordinateOptions {
/** 关闭菜单后执行的外部点击回调。 */
clickOutside?: OnClickOutsideHandler
/** 菜单挂载在目标之外时,可将弹层加入外部点击的忽略范围。 */
ignore?: OnClickOutsideOptions['ignore']
}
/**
@ -92,6 +95,15 @@ export const useContextmenuCoordinate = (
if (typeof current === 'object') current.clickOutside?.(event)
},
{
ignore: () => {
const current = toValue(options)
return typeof current === 'object'
? (toValue(current.ignore) ?? [])
: []
},
},
)
const cleanupContextmenu = useEventListener(

View File

@ -0,0 +1,219 @@
{
"result": "Result",
"empty": "No data",
"loading": "Loading",
"precision": {
"title": "Decimal precision",
"intro": "Edit the operands and inspect results at eight decimal places.",
"add": "Addition",
"subtract": "Subtraction",
"multiply": "Multiplication",
"divide": "Division",
"invalid": "Enter valid decimal numbers.",
"zero": "Divisors must be nonzero.",
"allocation": "Equal allocation",
"amount": "Amount",
"parts": "Number of shares"
},
"cache": {
"title": "Storage lab",
"intro": "Compare reading and writing the same key in two storage scopes.",
"write": "Write",
"read": "Read",
"remove": "Remove",
"scope": "Storage scope",
"key": "Key",
"value": "Value",
"missing": "No value for this key"
},
"form": {
"title": "Form validation",
"intro": "Submit the profile to see the submitted data beside the form.",
"profile": "Profile",
"name": "Name",
"age": "Age",
"date": "Date of birth",
"gender": "Gender",
"female": "Female",
"male": "Male",
"notes": "Notes",
"submit": "Submit profile",
"validateName": "Check name only",
"clear": "Clear validation",
"reset": "Reset",
"payload": "Submission",
"waiting": "Waiting for submission",
"submitted": "Submitted",
"invalid": "Check the highlighted fields",
"nameValid": "Name is valid",
"nameRequired": "Enter a name",
"ageRequired": "Enter an age between 0 and 120",
"dateRequired": "Choose a date of birth",
"genderRequired": "Choose a gender",
"sample": "Fill sample"
},
"request": {
"title": "Request lab",
"intro": "Inspect a manual response and compare request counts while typing in the throttle and debounce examples.",
"fixture": "Local sample data",
"fetch": "Fetch ticket",
"city": "Query by city",
"selectCity": "Choose a sample city",
"waiting": "Waiting for a request",
"failed": "Request failed. Try again.",
"throttle": "Throttle · 1 second",
"debounce": "Debounce · 1 second",
"sent": "{count} requests sent",
"input": "Type a few characters",
"last": "Latest response"
},
"iframe": {
"title": "Embedded content",
"intro": "Compare two loading strategies using the same local page.",
"eager": "Eager loading",
"lazy": "Lazy loading",
"loaded": "Loaded",
"pending": "Pending",
"mount": "Mount lazy example"
},
"modal": {
"title": "Dialogs",
"intro": "Open the presets to try dragging, fullscreen and a custom width.",
"card": "Card",
"dialog": "Dialog",
"fullscreen": "Fullscreen",
"record": "Sample ticket",
"open": {
"card": "Open card",
"dialog": "Open dialog",
"fullscreen": "Open fullscreen"
},
"width": "Card width",
"applyWidth": "Open at this width",
"createCard": "Create card programmatically",
"createDialog": "Create dialog programmatically",
"last": "Last closed"
},
"qr": {
"title": "QR code",
"intro": "Edit the content and style to regenerate the QR code.",
"controls": "Generation settings",
"content": "QR content",
"brand": "Center logo",
"status": "Display state",
"ready": "Ready",
"loading": "Loading",
"error": "Expired",
"download": "Download QR code",
"preview": "Scan preview",
"expired": "QR code expired",
"reload": "Reactivate",
"failed": "Could not generate the QR code",
"noText": "Enter text to generate a code",
"animated": "Animated background"
},
"barcode": {
"title": "Barcode",
"intro": "Switch encoding formats and edit the sample to see the live preview.",
"controls": "Encoding settings",
"format": "Format",
"content": "Barcode content",
"color": "Custom color",
"responsive": "Responsive width",
"preview": "Barcode preview",
"invalid": "This value does not match the selected format."
},
"flow": {
"title": "Flow diagram",
"intro": "Drag a node and inspect the graph, or switch to read-only mode.",
"review": "Review",
"done": "Done",
"canvas": "Workflow canvas",
"readonly": "Read-only",
"editable": "Editable",
"fit": "Fit view",
"reset": "Reset canvas",
"inspect": "Inspect graph",
"graph": "Current graph"
},
"drag": {
"title": "Draggable card",
"intro": "Open a card at a chosen position and compare the two drag boundaries.",
"stage": "Drag playground",
"position": "Initial position",
"enable": "Drag enabled",
"locked": "Drag locked",
"bounded": "Bounded card",
"body": "Page-wide card",
"bounds": "Container boundary"
},
"context": {
"title": "Context menu",
"intro": "Right-click the workspace or open the menu with the button.",
"target": "Ticket actions",
"open": "Open actions",
"last": "Last action",
"review": "Mark for review",
"archive": "Archive",
"restore": "Restore"
},
"nested": {
"draft": "Draft",
"note": "Temporary note",
"route": "Current route"
},
"detail": {
"name": "Name",
"address": "Address",
"phone": "Phone",
"action": "Actions",
"open": "Open details",
"back": "Back to people",
"missing": "Select a record from the list.",
"params": "Route parameters"
},
"directive": {
"ripple": "Click ripple",
"ripplePointer": "Ripple from pointer",
"rippleCenter": "Ripple from center",
"ellipsis": "Text truncation",
"single": "Single line",
"multi": "Multiple lines",
"copy1": "Copy text",
"copy2": "Copy custom content",
"copy": "Copy",
"throttle": "Throttle · 3 seconds",
"debounce": "Debounce · 3 seconds",
"calls": "Actual calls",
"run": "Trigger",
"disabled": "Disable interaction",
"nativeForm": "Native form",
"text": "Text selection",
"naive": "Naive UI controls",
"formInput": "Example input",
"submit": "Submit"
},
"chart": {
"sales": "Weekly sales trend",
"mount": "Render chart",
"dispose": "Dispose chart",
"update": "Refresh data",
"stopLoading": "Hide loading",
"showLoading": "Show loading",
"fixedTheme": "Fixed theme",
"pattern": "Show decals",
"hidePattern": "Hide decals",
"series": "Data state",
"revision": "Data revision {value}",
"unmounted": "Chart disposed"
},
"about": {
"title": "About Ray Template",
"intro": "Inspect the pinned dependency versions from the project manifest.",
"group": "Dependency group",
"runtime": "Runtime",
"development": "Development",
"search": "Search package names",
"noMatch": "No matching packages"
}
}

View File

@ -15,5 +15,43 @@
"layoutEyebrow": "WORKSPACE / LAYOUT",
"iconsEyebrow": "ASSETS / ICONS",
"livePreferences": "Live preview · Saved automatically",
"layoutControls": "Layout & display"
"layoutControls": "Layout & display",
"detailTitle": "Person details",
"multiOneTitle": "First-level menu example",
"multiOtherTitle": "Sibling menu example",
"multiNestedTitle": "Deep menu example",
"axiosDescription": "Compare manual requests, throttling and debouncing, and inspect each response.",
"precisionDescription": "Edit the numeric tags to explore decimal arithmetic and allocation. Examples use eight decimal places.",
"barcodeDescription": "Compare sizing, colors and encoding formats. Edit the text to see the barcode update.",
"qrcodeDescription": "Compare basic QR codes, loading states and reactive content.",
"formDescription": "Fill in the sample form to try field validation, reset and submission.",
"modalDescription": "Try draggable, full-screen, custom-width and programmatic dialogs.",
"directiveDescription": "Try truncation, copying, ripples, disabling and event rate limiting in one place.",
"contextDescription": "Right-click the area below to explore menu positioning and available actions.",
"iframeDescription": "Compare lazy and eager iframes to see when external content loads.",
"cacheDescription": "Enter a key and value to compare session and local storage.",
"flowDescription": "Drag nodes to rearrange the graph and switch to read-only mode to compare behavior.",
"dragDescription": "Open a floating card to compare starting positions and drag boundaries.",
"chartDescription": "Explore chart themes, loading states and custom rendering.",
"detailDescription": "This view adds a breadcrumb to the existing tab. Use navigation above to return to the list.",
"aboutDescription": "See the project version, maintenance links and dependencies.",
"multiOneDescription": "Switch between nested routes to observe view caching and form state.",
"multiOtherDescription": "Open sibling views in the sidebar to inspect their breadcrumb hierarchy.",
"multiNestedDescription": "Inspect navigation and view caching for a deeply nested route.",
"iframeTitle": "Embedded content",
"segmentTitle": "Segment",
"segmentDescription": "Switch widths and sizes to see the capsule move across segments with icons, hints and disabled options.",
"segmentOverview": "Overview",
"segmentReports": "Detailed reports",
"segmentPopover": "A contextual hint for this segment.",
"segmentDisabled": "Unavailable",
"segmentPlayground": "Playground",
"segmentWidth": "Width",
"segmentSize": "Size",
"segmentSelected": "Selected · {value}",
"segmentUncontrolled": "Default selection",
"segmentCustom": "Custom tab",
"segmentCustomLabel": "02 / Custom",
"scrollDescription": "Scroll to see cards fade and slide into view.",
"scrollCard": "Scroll example {index}"
}

View File

@ -0,0 +1,219 @@
{
"result": "结果",
"empty": "暂无数据",
"loading": "加载中",
"precision": {
"title": "数字精度",
"intro": "编辑操作数,对照八位小数的计算结果。",
"add": "加法",
"subtract": "减法",
"multiply": "乘法",
"divide": "除法",
"invalid": "请输入有效小数。",
"zero": "除数不能为 0。",
"allocation": "等额分配",
"amount": "金额",
"parts": "份数"
},
"cache": {
"title": "缓存实验室",
"intro": "对同一个键读写并比较两种存储范围。",
"write": "写入",
"read": "读取",
"remove": "删除",
"scope": "存储范围",
"key": "键名",
"value": "值",
"missing": "这个键还没有值"
},
"form": {
"title": "表单校验",
"intro": "填写档案后提交,右侧会显示实际提交的数据。",
"profile": "档案",
"name": "姓名",
"age": "年龄",
"date": "出生日期",
"gender": "性别",
"female": "女",
"male": "男",
"notes": "备注",
"submit": "提交档案",
"validateName": "仅校验姓名",
"clear": "清除校验",
"reset": "重置",
"payload": "提交数据",
"waiting": "等待提交",
"submitted": "提交成功",
"invalid": "请检查标记的字段",
"nameValid": "姓名校验通过",
"nameRequired": "请输入姓名",
"ageRequired": "请输入 0 至 120 岁的年龄",
"dateRequired": "请选择出生日期",
"genderRequired": "请选择性别",
"sample": "填入样例"
},
"request": {
"title": "请求实验室",
"intro": "查看手动请求的返回值,连续输入对比节流和防抖的实际发送次数。",
"fixture": "本地演示数据",
"fetch": "获取工单",
"city": "按城市查询",
"selectCity": "选择示例城市",
"waiting": "等待请求",
"failed": "请求失败,可重试",
"throttle": "节流 · 1 秒",
"debounce": "防抖 · 1 秒",
"sent": "已发送 {count} 次",
"input": "连续输入",
"last": "最近响应"
},
"iframe": {
"title": "嵌入内容",
"intro": "用同一个本地页面观察两种加载策略。",
"eager": "立即加载",
"lazy": "延迟加载",
"loaded": "已加载",
"pending": "等待加载",
"mount": "挂载延迟加载示例"
},
"modal": {
"title": "模态框",
"intro": "打开不同预设,试试拖拽、全屏和指定宽度。",
"card": "卡片",
"dialog": "对话框",
"fullscreen": "全屏",
"record": "示例工单",
"open": {
"card": "打开卡片",
"dialog": "打开对话框",
"fullscreen": "进入全屏"
},
"width": "卡片宽度",
"applyWidth": "按指定宽度打开",
"createCard": "命令式创建卡片",
"createDialog": "命令式创建对话框",
"last": "最近关闭"
},
"qr": {
"title": "二维码",
"intro": "输入内容并切换二维码样式,预览会随输入更新。",
"controls": "生成设置",
"content": "二维码内容",
"brand": "居中头像",
"status": "显示状态",
"ready": "正常",
"loading": "加载中",
"error": "已过期",
"download": "下载二维码",
"preview": "扫码预览",
"expired": "二维码已过期",
"reload": "重新启用",
"failed": "二维码生成失败",
"noText": "输入内容后生成",
"animated": "动态背景"
},
"barcode": {
"title": "条形码",
"intro": "切换编码格式并修改样例值,查看即时预览。",
"controls": "编码设置",
"format": "编码格式",
"content": "条码内容",
"color": "自定义颜色",
"responsive": "响应式宽度",
"preview": "条码预览",
"invalid": "内容不符合当前编码格式。"
},
"flow": {
"title": "流程图",
"intro": "拖动节点后读取画布数据,或切换只读模式。",
"review": "审核",
"done": "完成",
"canvas": "流程画布",
"readonly": "只读",
"editable": "可编辑",
"fit": "适应画布",
"reset": "重置画布",
"inspect": "读取图数据",
"graph": "当前图数据"
},
"drag": {
"title": "拖拽卡片",
"intro": "从指定位置打开卡片,比较容器内拖拽和页面范围拖拽。",
"stage": "拖拽试验台",
"position": "初始位置",
"enable": "允许拖拽",
"locked": "拖拽已锁定",
"bounded": "容器内卡片",
"body": "页面范围卡片",
"bounds": "容器拖拽边界"
},
"context": {
"title": "右键菜单",
"intro": "右击工作区打开菜单,也可用按钮选择操作。",
"target": "工单操作区",
"open": "打开操作菜单",
"last": "最近选择",
"review": "标记待审核",
"archive": "归档",
"restore": "恢复"
},
"nested": {
"draft": "草稿",
"note": "临时备注",
"route": "当前路由"
},
"detail": {
"name": "姓名",
"address": "地址",
"phone": "电话",
"action": "操作",
"open": "查看详情",
"back": "返回人员列表",
"missing": "请从列表选择一条记录。",
"params": "路由参数"
},
"directive": {
"ripple": "点击涟漪",
"ripplePointer": "从点击位置扩散",
"rippleCenter": "从中心扩散",
"ellipsis": "文本省略",
"single": "单行",
"multi": "多行",
"copy1": "复制文本",
"copy2": "复制自定义内容",
"copy": "复制",
"throttle": "节流 · 3 秒",
"debounce": "防抖 · 3 秒",
"calls": "实际执行次数",
"run": "触发",
"disabled": "禁用交互",
"nativeForm": "原生表单",
"text": "文本选择",
"naive": "Naive UI 控件",
"formInput": "示例输入框",
"submit": "提交"
},
"chart": {
"sales": "每周销售趋势",
"mount": "渲染图表",
"dispose": "卸载图表",
"update": "更新数据",
"stopLoading": "关闭加载",
"showLoading": "显示加载",
"fixedTheme": "固定主题示例",
"pattern": "显示贴花",
"hidePattern": "隐藏贴花",
"series": "数据状态",
"revision": "数据版本 {value}",
"unmounted": "已卸载"
},
"about": {
"title": "关于 Ray Template",
"intro": "从项目清单查看实际锁定的依赖版本。",
"group": "依赖分组",
"runtime": "生产依赖",
"development": "开发依赖",
"search": "搜索依赖名称",
"noMatch": "没有匹配的依赖"
}
}

View File

@ -15,5 +15,43 @@
"layoutEyebrow": "WORKSPACE / LAYOUT",
"iconsEyebrow": "ASSETS / ICONS",
"livePreferences": "即时预览 · 自动保存",
"layoutControls": "布局与显示"
"layoutControls": "布局与显示",
"detailTitle": "人员详情",
"multiOneTitle": "一级菜单示例",
"multiOtherTitle": "同级菜单示例",
"multiNestedTitle": "深层菜单示例",
"axiosDescription": "切换请求方式,对比手动执行、节流和防抖,并查看每次请求的结果。",
"precisionDescription": "用可编辑的数值标签验证小数运算和均分。示例默认保留八位小数。",
"barcodeDescription": "对比响应式、配色和编码格式,输入内容即可查看条形码的变化。",
"qrcodeDescription": "对比基础码、状态码和响应式内容,验证二维码从生成到更新的过程。",
"formDescription": "填写示例表单,试用字段验证、重置和提交。",
"modalDescription": "体验可拖拽、全屏、手动宽度和命令式打开的模态框。",
"directiveDescription": "在同一处体验文本省略、复制、涟漪、禁用和事件频率控制。",
"contextDescription": "在下方区域右键单击,检查菜单定位和可用操作。",
"iframeDescription": "对照延迟加载和立即加载的 iframe,观察外部内容的加载时机。",
"cacheDescription": "输入键和值,对比会话与本地缓存的读写。",
"flowDescription": "拖动节点调整布局,切换只读模式查看交互行为。",
"dragDescription": "在工作区中打开浮动卡片,比较不同初始位置与拖拽范围。",
"chartDescription": "对比基础图表、主题切换、加载状态和自定义渲染。",
"detailDescription": "这个页面在原标签页中追加面包屑,可使用上方导航回到列表。",
"aboutDescription": "了解项目版本、维护入口及使用的依赖。",
"multiOneDescription": "在多级菜单之间切换,观察页面缓存与表单状态。",
"multiOtherDescription": "通过侧栏进入同组页面,检查多级菜单与面包屑的对应关系。",
"multiNestedDescription": "查看深层路由对应的导航路径和页面缓存。",
"iframeTitle": "嵌入内容",
"segmentTitle": "分段器",
"segmentDescription": "切换宽度和尺寸,在带图标、提示和禁用项的分段器中观察选中滑块。",
"segmentOverview": "概览",
"segmentReports": "详细分析",
"segmentPopover": "提示信息跟随该选项。",
"segmentDisabled": "不可用",
"segmentPlayground": "交互试验台",
"segmentWidth": "宽度",
"segmentSize": "尺寸",
"segmentSelected": "当前选中 · {value}",
"segmentUncontrolled": "默认选中项",
"segmentCustom": "自定义标签",
"segmentCustomLabel": "02 / 自定义",
"scrollDescription": "向下滚动,观察卡片进入视口时的淡入和位移。",
"scrollCard": "滚动样例 {index}"
}

View File

@ -1,3 +0,0 @@
.axios-header__btn {
height: 64px;
}

View File

@ -1,165 +1,146 @@
import './index.scss'
import { getTypicCode, getWeather } from '@/api/demo/test'
import {
getRequestFixture,
getWeather,
requestFixtureUrl,
} from '@/api/demo/test'
import { useHookPlusRequest, useRequest } from '@/axios'
import { NButton, NCard, NFlex, NInput, NLayout } from 'naive-ui'
import { useI18n } from '@/hooks'
import { NButton, NCard, NFormItem, NInput, NSelect, NTag } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
const Axios = defineComponent({
export default defineComponent({
name: 'RAxios',
setup() {
const state = reactive({
weatherData: [],
inputCityValue: null,
throttleDemoInputValue: null,
debounceDemoInputValue: null,
weatherDemoInputValue: null,
})
const {
data: throttleDemoValue,
loading: throttleDemoLoading,
run: throttleDemoRun,
} = useHookPlusRequest(getTypicCode, {
throttleWait: 1000,
manual: true,
})
const {
data: debounceDemoValue,
loading: debounceDemoLoading,
run: debounceDemoRun,
} = useHookPlusRequest(getTypicCode, {
debounceWait: 1000,
manual: true,
})
const {
data: weatherDemoValue,
loading: weatherDemoLoading,
run: weatherDemoRun,
} = useHookPlusRequest(getWeather, {
throttleWait: 1000,
manual: true,
})
const {
data: demoData,
loading: demoLoading,
run: demoRun,
} = useRequest<{
title: string
}>(
{
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'get',
cancelConfig: {
cancel: true,
},
},
{
manual: true,
onError: () => {
window.$message.error('接口出现异常')
},
},
const { t } = useI18n('demoDetails')
const manual = useRequest<Awaited<ReturnType<typeof getRequestFixture>>>(
{ url: requestFixtureUrl, method: 'get', cancelConfig: { cancel: true } },
{ manual: true },
)
const city = ref<string | null>(null)
const weather = useHookPlusRequest(getWeather, { manual: true })
const cities = ['Hangzhou', 'Shanghai', 'Chengdu'].map((value) => ({
value,
label: value,
}))
const rateDemos = (['throttle', 'debounce'] as const).map((kind) => {
const input = ref('')
const sent = ref(0)
const inputId = useId()
const query = useHookPlusRequest(
async (value: string) => {
sent.value += 1
const { ticket } = await getRequestFixture()
return {
...toRefs(state),
throttleDemoValue,
throttleDemoLoading,
throttleDemoRun,
debounceDemoValue,
debounceDemoLoading,
debounceDemoRun,
weatherDemoValue,
weatherDemoLoading,
weatherDemoRun,
demoData,
demoLoading,
demoRun,
}
},
render() {
return (
<NLayout>
<NFlex vertical>
<h1>请求</h1>
<NCard>
<h2>useRequest</h2>
<p>支持配置化请求数据</p>
<h2>useHookPlusRequest</h2>
<p>
支持包裹一个拥有 promise 状态的异步函数,可以用来包裹一个 axios
请求返回值方法
</p>
return { value, ticket: ticket.id }
},
{
manual: true,
...(kind === 'throttle'
? { throttleWait: 1000 }
: { debounceWait: 1000 }),
},
)
return { kind, input, sent, inputId, query }
})
return () => (
<DemoPage
title={t('request.title')}
description={t('request.intro')}
meta={t('request.fixture')}
>
<div class="r-demo-grid">
<NCard title="useRequest">
<div class="r-demo-card-stack">
<NButton type="primary" onClick={() => manual.run()}>
{t('request.fetch')}
</NButton>
<DemoResult label={t('result')} error={!!manual.error.value}>
{manual.loading.value ? (
t('loading')
) : manual.error.value ? (
t('request.failed')
) : manual.data.value ? (
<pre>{JSON.stringify(manual.data.value.ticket, null, 2)}</pre>
) : (
t('request.waiting')
)}
</DemoResult>
</div>
</NCard>
<h1>使用 useRequest 获取</h1>
<NCard title="请求函数">
<h3>
1.基于 axios 封装,能够自动取消连续请求,避免重复渲染造成问题
</h3>
<h3>
2.打开控制台 =&gt; 网络 =&gt; 使用低速3g网络 =&gt;
查看控制台被取消的请求
</h3>
<h3>3.详情请查看文档</h3>
</NCard>
<NCard title="useRequest示例(手动触发)">
<NFlex vertical>
<NButton onClick={this.demoRun.bind(this)}>获取数据</NButton>
<h3>
结果:&nbsp;
{this.demoLoading ? '获取中...' : this.demoData?.title}
</h3>
</NFlex>
</NCard>
<h1>使用 useHookPlusRequest 获取</h1>
<NCard title="节流">
<NFlex vertical>
<NInput
v-model:value={this.throttleDemoInputValue}
onUpdateValue={() => {
this.throttleDemoRun()
<NCard title={t('request.city')}>
<div class="r-demo-card-stack">
<NSelect
value={city.value}
options={cities}
placeholder={t('request.selectCity')}
onUpdateValue={(value) => {
city.value = value
weather.run(value)
}}
/>
<h3>不论触发多少次,一秒钟之内仅会触发一次</h3>
<h3>
当前状态:&nbsp;
{this.throttleDemoLoading ? '获取中...' : '获取成功!!!'}
</h3>
</NFlex>
<DemoResult label={t('result')} error={!!weather.error.value}>
{weather.loading.value
? t('loading')
: weather.error.value
? t('request.failed')
: weather.data.value
? `${weather.data.value.temperature} °C · ${weather.data.value.humidity}% RH`
: t('request.waiting')}
</DemoResult>
</div>
</NCard>
<NCard title="防抖">
<NFlex vertical>
<NInput
v-model:value={this.debounceDemoInputValue}
onUpdateValue={() => {
this.debounceDemoRun()
}}
/>
<h3>一秒后才会执行,如果中途重新请求,则会重新计时</h3>
<h3>
当前状态:&nbsp;
{this.debounceDemoLoading ? '获取中...' : '获取成功!!!'}
</h3>
</NFlex>
</NCard>
<NCard title="获取气候">
<NFlex vertical>
<NInput
v-model:value={this.weatherDemoInputValue}
onUpdateValue={(val) => {
this.weatherDemoRun(val)
}}
/>
<h3>该示例演示了如何根据动态值获取数据</h3>
<h3>
当前状态:&nbsp;
{this.weatherDemoLoading ? '获取中...' : '获取成功!!!'}
</h3>
</NFlex>
</NCard>
</NFlex>
</NLayout>
{rateDemos.map(({ kind, input, sent, inputId, query }) => (
<NCard key={kind} title={t(`request.${kind}`)}>
{{
'header-extra': () => (
<NTag size="small" bordered={false}>
{t('request.sent', { count: sent.value })}
</NTag>
),
default: () => (
<div class="r-demo-card-stack">
<NFormItem
label={t('request.input')}
labelProps={{ for: inputId }}
showFeedback={false}
>
<NInput
value={input.value}
inputProps={{ id: inputId }}
onUpdateValue={(value) => {
input.value = value
if (value.trim()) query.run(value)
else query.cancel()
}}
/>
</NFormItem>
<DemoResult
label={t('request.last')}
error={!!query.error.value}
>
{query.loading.value ? (
t('loading')
) : query.error.value ? (
t('request.failed')
) : query.data.value ? (
<code>
{query.data.value.value} · {query.data.value.ticket}
</code>
) : (
t('request.waiting')
)}
</DemoResult>
</div>
),
}}
</NCard>
))}
</div>
</DemoPage>
)
},
})
export default Axios

View File

@ -1,133 +1,121 @@
import { RBarcode } from '@/components'
import {
NAlert,
NCard,
NFlex,
NGrid,
NGridItem,
NInput,
NSwitch,
} from 'naive-ui'
import { useI18n } from '@/hooks'
import { NCard, NFlex, NFormItem, NInput, NSelect, NSwitch } from 'naive-ui'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'
const samples = {
CODE128: 'RAY-024',
pharmacode: '1234',
codabar: 'A1234B',
} as const
const formats = Object.keys(samples).map((value) => ({ value, label: value }))
export default defineComponent({
name: 'BarcodeDemo',
setup() {
const baseOptions = {
width: 4,
}
const { t } = useI18n('demoDetails')
const format = ref<keyof typeof samples>('CODE128')
const text = ref<string>(samples.CODE128)
const loading = ref(false)
const text = ref('RayTemplate')
const colored = ref(false)
const responsive = ref(false)
const failed = ref(false)
const id = useId()
return {
baseOptions,
loading,
text,
}
},
render() {
const { baseOptions } = this
return (
<NGrid cols={2} xGap={12} yGap={12}>
<NGridItem span={2}>
<NCard title="详细配置项说明">
点击查看详细配置项:
<a href="https://github.com/lindell/JsBarcode/wiki/Options">
js-barcode options
</a>
。
return () => (
<DemoPage title={t('barcode.title')} description={t('barcode.intro')}>
<div class="r-demo-grid">
<NCard title={t('barcode.controls')}>
<div class="r-demo-card-stack">
<NFormItem label={t('barcode.format')} showFeedback={false}>
<NSelect
value={format.value}
options={formats}
onUpdateValue={(value: keyof typeof samples) => {
format.value = value
text.value = samples[value]
failed.value = false
}}
/>
</NFormItem>
<NFormItem
label={t('barcode.content')}
labelProps={{ for: id }}
showFeedback={false}
>
<NInput
v-model:value={text.value}
maxlength={24}
inputProps={{ id }}
/>
</NFormItem>
<NFlex>
<label>
<NSwitch
v-model:value={colored.value}
aria-label={t('barcode.color')}
/>{' '}
{t('barcode.color')}
</label>
<label>
<NSwitch
v-model:value={responsive.value}
aria-label={t('barcode.responsive')}
/>{' '}
{t('barcode.responsive')}
</label>
<label>
<NSwitch
v-model:value={loading.value}
aria-label={t('loading')}
/>{' '}
{t('loading')}
</label>
</NFlex>
</div>
</NCard>
</NGridItem>
<NGridItem span={1}>
<NCard title="根据尺寸自动更新的条形码">
<RBarcode
text="RayTemplate"
options={{
...baseOptions,
}}
responsive
/>
<NCard title={t('barcode.preview')}>
<div class="r-demo-card-stack">
<div class="r-demo-artifact r-demo-artifact--barcode">
{text.value.trim() && (
<RBarcode
key={`${format.value}-${colored.value}-${responsive.value}`}
text={text.value}
format={format.value}
responsive={responsive.value}
width={responsive.value ? 'responsive' : 'auto'}
barcodeRender="svg"
loading={loading.value}
watchText
style={{ visibility: failed.value ? 'hidden' : 'visible' }}
options={{
width: 2,
height: 58,
lineColor: colored.value ? '#0b6b73' : '#182436',
}}
onSuccess={() => {
failed.value = false
}}
onError={() => {
failed.value = true
}}
/>
)}
</div>
<DemoResult label={format.value} error={failed.value}>
{failed.value ? (
t('barcode.invalid')
) : text.value.trim() ? (
<code>{text.value}</code>
) : (
t('empty')
)}
</DemoResult>
</div>
</NCard>
</NGridItem>
<NGridItem span={1}>
<NCard title="自定义颜色条形码">
<RBarcode
text="RayTemplate"
options={{
...baseOptions,
lineColor: 'red',
}}
/>
</NCard>
</NGridItem>
<NGridItem span={1}>
<NCard title="pharmacode 模式">
<NFlex vertical>
<NAlert type="warning" title="注意">
该模式下,条形码只能渲染有效数值,否则将会渲染失败。可以查看官网说明:
<a href="https://github.com/lindell/JsBarcode/wiki/pharmacode">
pharmacode
</a>
。
</NAlert>
<RBarcode
text="1234"
format="pharmacode"
options={{
width: 4,
height: 40,
displayValue: false,
background: '#eee',
}}
/>
</NFlex>
</NCard>
</NGridItem>
<NGridItem span={1}>
<NCard title="codabar 模式">
<NFlex vertical>
<NAlert type="warning" title="注意">
该模式下,需要注意 text 中的特殊字符,可以查看官网说明:
<a href="https://github.com/lindell/JsBarcode/wiki/codabar">
codabar
</a>
。
</NAlert>
<RBarcode
text="1234"
format="codabar"
options={{
width: 4,
height: 40,
displayValue: false,
background: '#eee',
}}
/>
</NFlex>
</NCard>
</NGridItem>
<NGridItem span={1}>
<NCard title="有状态的条形码">
<NFlex vertical size="large" justify="flex-start" inline>
<NSwitch v-model:value={this.loading} style="width: fit-content">
{{
checked: () => 'loading...',
unchecked: () => 'success!',
}}
</NSwitch>
<RBarcode text="RayTemplate" loading={this.loading} />
</NFlex>
</NCard>
</NGridItem>
<NGridItem span={1}>
<NCard title="watchText 主动监听 text 变化">
<NFlex vertical>
<NInput v-model:value={this.text} />
<RBarcode text={this.text} watchText />
</NFlex>
</NCard>
</NGridItem>
</NGrid>
</div>
</DemoPage>
)
},
})

View File

@ -1,101 +1,117 @@
import { useI18n } from '@/hooks'
import { getStorage, hasStorage, removeStorage, setStorage } from '@/utils'
import {
NButton,
NCard,
NFlex,
NFormItem,
NInput,
NInputGroup,
NInputGroupLabel,
NRadioButton,
NRadioGroup,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
export default defineComponent({
name: 'CacheDemo',
setup() {
const nameValue = ref('Ray')
const currentPrefix = ref('ray:')
const { t } = useI18n('demoDetails')
const value = ref('Ray')
const scope = ref<'sessionStorage' | 'localStorage'>('sessionStorage')
const suffix = ref('name')
const selectedKey = computed(() => `ray:showcase:${suffix.value.trim()}`)
const current = ref<string | null>(null)
const operation = ref('cache.read')
const keyId = useId()
const valueId = useId()
return {
nameValue,
currentPrefix,
const read = () => {
current.value = hasStorage(selectedKey.value, scope.value)
? getStorage<string>(selectedKey.value, scope.value)
: null
}
},
render() {
return (
<NCard title="cache 工具包示例">
{{
default: () => (
<NFlex vertical>
<h3>点击 setStorage 按钮,设置缓存示例</h3>
<NInputGroup>
<NInputGroupLabel>设置缓存内容</NInputGroupLabel>
watch([selectedKey, scope], read, { immediate: true })
return () => (
<DemoPage title={t('cache.title')} description={t('cache.intro')}>
<div class="r-demo-grid">
<NCard title={t('cache.write')}>
<div class="r-demo-card-stack">
<NRadioGroup
v-model:value={scope.value}
aria-label={t('cache.scope')}
>
<NRadioButton value="sessionStorage">
sessionStorage
</NRadioButton>
<NRadioButton value="localStorage">localStorage</NRadioButton>
</NRadioGroup>
<NFormItem
label={t('cache.key')}
labelProps={{ for: keyId }}
showFeedback={false}
>
<NInput
v-model:value={this.nameValue}
placeholder="请输入姓名"
inputProps={{ id: keyId }}
v-model:value={suffix.value}
maxlength={32}
/>
</NInputGroup>
<NInputGroup>
<NInputGroupLabel>设置前缀</NInputGroupLabel>
</NFormItem>
<NFormItem
label={t('cache.value')}
labelProps={{ for: valueId }}
showFeedback={false}
>
<NInput
v-model:value={this.currentPrefix}
placeholder="请输入前缀"
inputProps={{ id: valueId }}
v-model:value={value.value}
/>
</NInputGroup>
</NFlex>
),
action: () => (
<NFlex>
<NButton
onClick={() => {
setStorage('name', this.nameValue, 'sessionStorage', {
prefix: true,
prefixKey: this.currentPrefix,
})
window.$message.success('设置成功')
}}
>
setStorage
</NButton>
<NButton
onClick={() => {
const name = getStorage('name', 'sessionStorage', {
prefix: true,
prefixKey: this.currentPrefix,
})
window.$message.success(`获取到的姓名为:${name}`)
}}
>
getStorage
</NButton>
<NButton
onClick={() => {
removeStorage('name', 'sessionStorage', {
prefix: true,
prefixKey: this.currentPrefix,
})
window.$message.success('删除成功')
}}
>
removeStorage
</NButton>
<NButton
onClick={() => {
const cacheKey = hasStorage('name', 'sessionStorage', {
prefix: true,
prefixKey: this.currentPrefix,
})
window.$message.success(`是否存在:${cacheKey}`)
}}
>
hasStorage
</NButton>
</NFlex>
),
}}
</NCard>
</NFormItem>
<NFlex>
<NButton
type="primary"
disabled={!suffix.value.trim()}
onClick={() => {
setStorage(selectedKey.value, value.value, scope.value)
operation.value = 'cache.write'
read()
}}
>
{t('cache.write')}
</NButton>
<NButton
onClick={() => {
operation.value = 'cache.read'
read()
}}
>
{t('cache.read')}
</NButton>
<NButton
onClick={() => {
removeStorage(selectedKey.value, scope.value)
operation.value = 'cache.remove'
read()
}}
>
{t('cache.remove')}
</NButton>
</NFlex>
</div>
</NCard>
<NCard title={t('result')}>
<DemoResult label={t(operation.value)}>
<pre>{selectedKey.value}</pre>
<pre>
{current.value === null
? t('cache.missing')
: JSON.stringify(current.value)}
</pre>
</DemoResult>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -0,0 +1,58 @@
import { useI18n } from '@/hooks'
import { NButton, NCard, NFormItem, NInput, NTag } from 'naive-ui'
import DemoPage from './DemoPage'
import DemoResult from './DemoResult'
export default defineComponent({
name: 'CacheRouteExample',
props: {
title: { type: String, required: true },
description: { type: String, required: true },
},
setup(props) {
const { t } = useI18n('demoDetails')
const route = useRoute()
const note = ref('')
const id = useId()
return () => (
<DemoPage title={props.title} description={props.description}>
<div class="r-demo-grid">
<NCard title={t('nested.draft')}>
<div class="r-demo-card-stack">
<NFormItem
label={t('nested.note')}
labelProps={{ for: id }}
showFeedback={false}
>
<NInput
type="textarea"
v-model:value={note.value}
inputProps={{ id }}
/>
</NFormItem>
<NButton
onClick={() => {
note.value = ''
}}
>
{t('form.reset')}
</NButton>
</div>
</NCard>
<NCard title={t('nested.route')}>
<div class="r-demo-card-stack">
<code>{route.path}</code>
<NTag type="info" bordered={false}>
KeepAlive
</NTag>
<DemoResult label={t('nested.note')}>
{note.value || t('empty')}
</DemoResult>
</div>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -0,0 +1,18 @@
export default defineComponent({
name: 'DemoResult',
props: {
label: { type: String, required: true },
error: Boolean,
},
setup(props, { slots }) {
return () => (
<div
class={['r-demo-result', { 'r-demo-result--error': props.error }]}
role="status"
>
<span class="r-demo-result__label">{props.label}</span>
<div class="r-demo-result__value">{slots.default?.()}</div>
</div>
)
},
})

View File

@ -80,3 +80,143 @@
grid-template-columns: minmax(300px, 0.9fr) minmax(0, 1.1fr);
}
}
.r-demo-grid {
display: grid;
grid-template-columns: minmax(0, 1fr);
align-items: stretch;
gap: 20px;
> * {
min-inline-size: 0;
}
&__wide {
grid-column: 1 / -1;
}
}
@container (min-width: 760px) {
.r-demo-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.r-demo-stage {
display: grid;
min-block-size: 220px;
place-items: center;
padding: 20px;
border: 1px dashed var(--r-control-border);
border-radius: var(--r-radius);
background-color: var(--r-surface-muted);
background-image: radial-gradient(
var(--r-control-border) 0.6px,
transparent 0.6px
);
background-size: 16px 16px;
color: var(--r-text);
text-align: center;
&--drag {
min-block-size: 380px;
margin-block-end: 20px;
}
}
.r-demo-card-stack {
display: grid;
gap: 16px;
min-width: 0;
}
.r-demo-artifact {
display: grid;
place-items: center;
min-width: 0;
min-height: 150px;
padding: 12px;
border: 1px solid var(--r-line);
border-radius: 10px;
background: #fff;
color: #182436;
overflow: auto;
> * {
max-inline-size: 100%;
}
}
.r-demo-result {
min-width: 0;
display: grid;
gap: 6px;
padding: 12px 14px;
border: 1px solid var(--r-line);
border-radius: 8px;
background: var(--r-surface-muted);
color: var(--r-text);
&--error {
border-inline-start: 3px solid #d05055;
}
&__label {
color: var(--r-text-secondary);
font-size: 12px;
font-weight: 600;
}
&__value {
overflow-wrap: anywhere;
font-variant-numeric: tabular-nums;
pre {
margin: 0;
white-space: pre-wrap;
font-family: var(--r-font-mono);
}
}
}
.r-demo-modal-sketch {
min-height: 112px;
display: grid;
place-items: center;
border-radius: 8px;
background: var(--r-canvas);
span {
inline-size: 60%;
block-size: 68px;
border: 1px solid var(--r-control-border);
border-block-start: 10px solid var(--r-theme-primary-color);
border-radius: 5px;
background: var(--r-surface);
}
&--dialog span {
inline-size: 40%;
block-size: 50px;
}
&--fullscreen span {
inline-size: calc(100% - 16px);
block-size: 96px;
}
}
.r-demo-artifact--barcode {
grid-template-columns: minmax(0, 1fr);
svg {
max-inline-size: 100%;
}
}
.r-demo-flow-canvas {
min-width: 0;
overflow: hidden;
border: 1px solid var(--r-line);
border-radius: 8px;
}

View File

@ -1,81 +1,59 @@
import { useContextmenuCoordinate } from '@/hooks'
import { NCard, NDropdown, NFlex } from 'naive-ui'
import { useContextmenuCoordinate, useI18n } from '@/hooks'
import { NButton, NCard, NDropdown } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
const actions = ['review', 'archive', 'restore'] as const
export default defineComponent({
name: 'ContextMenuDemo',
setup() {
const demoOneRef = ref<HTMLElement>()
const demoOneShow = ref(false)
const options = ref([
{
label: '杰·盖茨比',
key: 'jay gatsby',
},
{
label: '黛西·布坎南',
key: 'daisy buchanan',
},
{
type: 'divider',
key: 'd1',
},
{
label: '尼克·卡拉威',
key: 'nick caraway',
},
])
const { x, y, show, updateShow } = useContextmenuCoordinate(demoOneRef)
const clickOutside = (e: MouseEvent) => {
e.preventDefault()
const { t } = useI18n('demoDetails')
const stage = useTemplateRef<HTMLElement>('stage')
const { x, y, show, updateShow } = useContextmenuCoordinate(stage, {
ignore: ['.r-demo-context-popup'],
})
const selected = ref<string>()
const options = computed(() =>
actions.map((key) => ({ key, label: t(`context.${key}`) })),
)
const select = (key: string) => {
selected.value = key
updateShow(false)
}
return {
demoOneRef,
demoOneShow,
x,
y,
show,
options,
clickOutside,
updateShow,
}
},
render() {
const { x, y, show } = this
const { clickOutside, updateShow } = this
return (
<NFlex vertical>
<NCard title="useContextmenuCoordinate + NDropdown 实现右键菜单">
<NFlex vertical>
<h3>默认点击元素外部会关闭菜单。</h3>
<div
ref="demoOneRef"
style="width: 100%; height: 200px; background-color: rgba(0, 128, 0, 0.5)"
>
右击
return () => (
<DemoPage title={t('context.title')} description={t('context.intro')}>
<NCard title="RAY-024">
<div class="r-demo-card-stack">
<div ref="stage" class="r-demo-stage">
<div class="r-demo-card-stack">
<strong>{t('context.target')}</strong>
<NDropdown
options={options.value}
trigger="click"
onSelect={select}
>
<NButton secondary>{t('context.open')}</NButton>
</NDropdown>
</div>
</div>
</NFlex>
<DemoResult label={t('context.last')}>
{selected.value ? t(`context.${selected.value}`) : t('empty')}
</DemoResult>
</div>
</NCard>
<NDropdown
show={show}
x={x}
y={y}
options={this.options}
show={show.value}
x={x.value}
y={y.value}
options={options.value}
trigger="manual"
placement="bottom-start"
onSelect={(value, option) => {
window.$message.info(`选中了 ${option.label}`)
updateShow(false)
}}
onClickoutside={clickOutside.bind(this)}
menuProps={() => ({ class: 'r-demo-context-popup' })}
onSelect={select}
onClickoutside={() => updateShow(false)}
/>
</NFlex>
</DemoPage>
)
},
})

View File

@ -10,8 +10,9 @@ import {
NInputGroup,
NInputNumber,
NSwitch,
NTag,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
const RDirective = defineComponent({
name: 'RDirective',
@ -22,6 +23,7 @@ const RDirective = defineComponent({
throttleBtnClickCount: 0,
debounceBtnClickCount: 0,
disabledValue: false,
formCount: 0,
})
const ellipsisLineClamp = ref(2)
@ -39,163 +41,173 @@ const RDirective = defineComponent({
},
render() {
return (
<NFlex>
<NCard title="指令">该页面展示如何使用已封装好的指令</NCard>
<NCard title="水波纹">
<NFlex vertical>
<NAlert title="modifiers" type="info">
你可以手动显示的声明水波纹效果,默认为 circle。你可以手动的声明为
center。
</NAlert>
<NAlert title="vue template" type="success">
"v-ripple.center" 或者 "v-ripple.circle"。
</NAlert>
<NAlert title="tsx" type="success">
{JSON.stringify(`v-ripple={[true, ['center']]}`)} 或者
{JSON.stringify(`v-ripple={[true, ['circle']]}`)}。
</NAlert>
<NFlex>
<NTag v-ripple type="success" size="large">
水波纹效果的Tag
</NTag>
<NTag v-ripple type="warning" size="large">
水波纹效果的Tag
</NTag>
<NTag v-ripple type="error" size="large">
水波纹效果的Tag
</NTag>
<NButton v-ripple type="info">
水波纹效果的Button
</NButton>
<div
style="height: 20px; line-height: 20px;text-align: center; border: 1px solid; padding: 6px;"
v-ripple={[true, ['center']]}
>
原生元素绑定水波纹效果,并且手动绑定 modifiers 为 center
</div>
<DemoPage
title={this.$t('menu.Directive')}
description={this.$t('showcase.directiveDescription')}
eyebrow="RAY TEMPLATE / EXAMPLES"
>
<div class="r-demo-grid">
<NCard title={this.$t('demoDetails.directive.ripple')}>
<NFlex vertical>
<NFlex>
<NButton v-ripple type="info">
{this.$t('demoDetails.directive.ripplePointer')}
</NButton>
<NButton v-ripple={[true, ['center']]}>
{this.$t('demoDetails.directive.rippleCenter')}
</NButton>
</NFlex>
</NFlex>
</NFlex>
</NCard>
<NCard title="文本省略">
<NFlex vertical>
<NCard title="单行省略">
<div
v-ellipsis={{
type: 'block',
width: '100px',
}}
>
我是一段很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本。
</div>
</NCard>
<NCard title="多行省略">
<NFlex vertical size="large">
<NAlert title="注意" type="warning">
该方法基于非标准属性实现(-webkit-line-clamp),可能会有兼容性问题,所以请谨慎使用。
详情参考:
<a href="https://caniuse.com/?search=line-clamp">can i use</a>
</NAlert>
</NCard>
<NCard title={this.$t('demoDetails.directive.ellipsis')}>
<NFlex vertical>
<NCard title={this.$t('demoDetails.directive.single')}>
<div
v-ellipsis={{
type: 'line',
type: 'block',
width: '100px',
line: this.ellipsisLineClamp,
}}
>
我是一段很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本。
</div>
<NInputNumber v-model:value={this.ellipsisLineClamp} min={1} />
</NFlex>
</NCard>
</NFlex>
</NCard>
<NCard title="文本复制示例一">
<NInputGroup>
<NInput v-model:value={this.copyValueOne} />
<NButton v-copy={this.copyValueOne}>复制</NButton>
</NInputGroup>
</NCard>
<NCard title="文本复制示例二">
<NInputGroup>
<NInput v-model:value={this.copyValueTwo} />
<NButton v-copy={this.copyValueTwo}>复制</NButton>
</NInputGroup>
</NCard>
<NCard title="节流">
<NFlex vertical>
<NButton
v-throttle={{
func: this.updateDemoValue.bind(null, 'throttleBtnClickCount'),
trigger: 'click',
wait: 3000,
options: {},
}}
>
点击执行
</NButton>
<p>我执行了{this.throttleBtnClickCount}次</p>
<p>该方法 3s 内仅会执行一次</p>
</NFlex>
</NCard>
<NCard title="防抖">
<NFlex vertical>
<NButton
v-debounce={{
func: this.updateDemoValue.bind(null, 'debounceBtnClickCount'),
trigger: 'click',
wait: 3000,
options: {},
}}
>
点击执行
</NButton>
<p>我执行了{this.debounceBtnClickCount}次</p>
<p>该方法将延迟 3s 执行</p>
</NFlex>
</NCard>
<NCard title="禁用">
<NFlex vertical>
<NSwitch v-model:value={this.disabledValue}>
{{
checked: () => '取消',
unchecked: () => '禁用',
}}
</NSwitch>
<NCard title="描述">
<p>
该指令会强制禁用(通过 css 层面)禁用元素交互。但是 naive ui
组件提供了完整的 disabled
属性,所以在组件库有禁用需求时,直接调用组件库 disabled
属性即可。但是值得注意的是,该指令优先级最高,会覆盖组件
disabled 属性。
</p>
</NCard>
<NCard title="原生表单">
<form v-disabled={this.disabledValue}>
<input type="text" placeholder="请输入" />
<button>提交</button>
</form>
</NCard>
<NCard title="文本内容">
<NFlex vertical>
<p v-disabled={this.disabledValue}>我是可以被禁用的文本内容</p>
</NFlex>
</NCard>
<NCard title="naive 组件">
<NFlex vertical justify="start">
<NForm v-disabled={this.disabledValue}>
<NFormItem>
<NInput />
</NFormItem>
</NForm>
<NButton v-disabled={this.disabledValue}>按钮</NButton>
<NSwitch v-disabled={this.disabledValue}></NSwitch>
</NFlex>
</NCard>
</NFlex>
</NCard>
</NFlex>
</NCard>
<NCard title={this.$t('demoDetails.directive.multi')}>
<NFlex vertical size="large">
<NAlert title="注意" type="warning">
该方法基于非标准属性实现(-webkit-line-clamp),可能会有兼容性问题,所以请谨慎使用。
详情参考:
<a href="https://caniuse.com/?search=line-clamp">
can i use
</a>
</NAlert>
<div
v-ellipsis={{
type: 'line',
width: '100px',
line: this.ellipsisLineClamp,
}}
>
我是一段很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本。
</div>
<NInputNumber
v-model:value={this.ellipsisLineClamp}
min={1}
/>
</NFlex>
</NCard>
</NFlex>
</NCard>
<NCard title={this.$t('demoDetails.directive.copy1')}>
<NInputGroup>
<NInput v-model:value={this.copyValueOne} />
<NButton v-copy={this.copyValueOne}>
{this.$t('demoDetails.directive.copy')}
</NButton>
</NInputGroup>
</NCard>
<NCard title={this.$t('demoDetails.directive.copy2')}>
<NInputGroup>
<NInput v-model:value={this.copyValueTwo} />
<NButton v-copy={this.copyValueTwo}>
{this.$t('demoDetails.directive.copy')}
</NButton>
</NInputGroup>
</NCard>
<NCard title={this.$t('demoDetails.directive.throttle')}>
<NFlex vertical>
<NButton
v-throttle={{
func: this.updateDemoValue.bind(
null,
'throttleBtnClickCount',
),
trigger: 'click',
wait: 3000,
options: {},
}}
>
{this.$t('demoDetails.directive.run')}
</NButton>
<DemoResult label={this.$t('demoDetails.directive.calls')}>
{this.throttleBtnClickCount}
</DemoResult>
</NFlex>
</NCard>
<NCard title={this.$t('demoDetails.directive.debounce')}>
<NFlex vertical>
<NButton
v-debounce={{
func: this.updateDemoValue.bind(
null,
'debounceBtnClickCount',
),
trigger: 'click',
wait: 3000,
options: {},
}}
>
{this.$t('demoDetails.directive.run')}
</NButton>
<DemoResult label={this.$t('demoDetails.directive.calls')}>
{this.debounceBtnClickCount}
</DemoResult>
</NFlex>
</NCard>
<NCard title={this.$t('demoDetails.directive.disabled')}>
<NFlex vertical>
<NSwitch v-model:value={this.disabledValue}>
{{
checked: () => '取消',
unchecked: () => '禁用',
}}
</NSwitch>
<NCard title={this.$t('demoDetails.directive.nativeForm')}>
<form
v-disabled={this.disabledValue}
onSubmit={(event) => {
event.preventDefault()
this.formCount += 1
}}
>
<NInputGroup>
<NInput
inputProps={{
'aria-label': this.$t(
'demoDetails.directive.formInput',
),
}}
/>
<NButton attrType="submit">
{this.$t('demoDetails.directive.submit')}
</NButton>
</NInputGroup>
</form>
<DemoResult label={this.$t('demoDetails.directive.calls')}>
{this.formCount}
</DemoResult>
</NCard>
<NCard title={this.$t('demoDetails.directive.text')}>
<NFlex vertical>
<p v-disabled={this.disabledValue}>
我是可以被禁用的文本内容
</p>
</NFlex>
</NCard>
<NCard title={this.$t('demoDetails.directive.naive')}>
<NFlex vertical justify="start">
<NForm v-disabled={this.disabledValue}>
<NFormItem>
<NInput />
</NFormItem>
</NForm>
<NButton v-disabled={this.disabledValue}>按钮</NButton>
<NSwitch v-disabled={this.disabledValue}></NSwitch>
</NFlex>
</NCard>
</NFlex>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -1,97 +1,92 @@
import { RDraggableCard } from '@/components'
import type { DefaultPosition } from '@/components'
import { NButton, NCard, NFlex, NRadio, NRadioGroup, NSwitch } from 'naive-ui'
import { useI18n } from '@/hooks'
import { NButton, NCard, NFlex, NSelect, NSwitch, NTag } from 'naive-ui'
import DemoPage from './components/DemoPage'
const positions = [
'center',
'top-center',
'bottom-center',
'top-left',
'top-right',
'bottom-left',
'bottom-right',
] as const
const options = positions.map((value) => ({ label: value, value }))
export default defineComponent({
name: 'DraggableCardDemo',
setup() {
const card3 = ref(false)
const domRef = useTemplateRef<HTMLElement>('domRef')
const positionRadioOptions = [
{ label: 'center', value: 'center' },
{ label: 'top-center', value: 'top-center' },
{ label: 'bottom-center', value: 'bottom-center' },
{ label: 'top-left', value: 'top-left' },
{ label: 'top-right', value: 'top-right' },
{ label: 'bottom-left', value: 'bottom-left' },
{ label: 'bottom-right', value: 'bottom-right' },
]
const positionRadioValue = ref('center')
const card3Dad = ref(true)
const { t } = useI18n('demoDetails')
const target = useTemplateRef<HTMLElement>('target')
const position = ref<DefaultPosition>('center')
const draggable = ref(true)
const scope = ref<'bounded' | 'body' | null>(null)
return {
card3,
card3Dad,
domRef,
positionRadioOptions,
positionRadioValue,
}
},
render() {
const { card3, domRef, positionRadioOptions } = this
return (
<div>
<div
ref="domRef"
style={{
width: '100%',
height: '400px',
backgroundColor: 'rgba(255, 10, 20, 1)',
}}
></div>
<RDraggableCard animation title="Body">
我被限制在 body 中。
</RDraggableCard>
{card3 ? (
<RDraggableCard
animation
title="Custom Container"
restrictionElement={domRef}
closable
onClose={() => (this.card3 = false)}
defaultPosition={this.positionRadioValue as DefaultPosition}
dad={this.card3Dad}
>
{{
default: () =>
'我被限制在红色区域中。并且我支持 NCard 的所有配置与插槽。',
'header-extra': () => '其实我就是 NCard 封装的',
footer: () => '我支持 footer 插槽',
action: () => '我支持 action 插槽',
}}
</RDraggableCard>
) : null}
<NCard title="显示与隐藏卡片">
<NFlex vertical>
<NFlex>
<NSwitch v-model:value={this.card3Dad}>
{{
checked: () => '拖拽',
unchecked: () => '禁用',
return () => (
<DemoPage title={t('drag.title')} description={t('drag.intro')}>
<NCard title={t('drag.stage')}>
<div class="r-demo-card-stack">
<NFlex align="center">
<NSelect
value={position.value as string}
options={options}
style={{ width: '150px' }}
aria-label={t('drag.position')}
onUpdateValue={(value: DefaultPosition) => {
position.value = value
}}
</NSwitch>
</NFlex>
<NFlex>
<NRadioGroup v-model:value={this.positionRadioValue}>
{positionRadioOptions.map((curr) => (
<NRadio key={curr.value} value={curr.value}>
{curr.label}
</NRadio>
))}
</NRadioGroup>
</NFlex>
<NFlex>
/>
<NSwitch
v-model:value={draggable.value}
aria-label={t('drag.enable')}
/>
<NTag bordered={false}>
{draggable.value ? t('drag.enable') : t('drag.locked')}
</NTag>
<NButton
type="primary"
onClick={() => (this.card3 = !this.card3)}
onClick={() => {
scope.value = scope.value === 'bounded' ? null : 'bounded'
}}
>
点一下试试
{t('drag.bounded')}
</NButton>
<NButton
onClick={() => {
scope.value = scope.value === 'body' ? null : 'body'
}}
>
{t('drag.body')}
</NButton>
</NFlex>
</NFlex>
<div ref="target" class="r-demo-stage r-demo-stage--drag">
<span>{t('drag.bounds')}</span>
</div>
</div>
</NCard>
</div>
{scope.value && target.value && (
<RDraggableCard
key={`${scope.value}-${String(position.value)}`}
restrictionElement={
scope.value === 'bounded' ? target.value : 'body'
}
width="min(220px, calc(100vw - 56px))"
defaultPosition={position.value}
title={t(`drag.${scope.value}`)}
closable
dad={draggable.value}
onClose={() => {
scope.value = null
}}
>
<NTag bordered={false}>
{draggable.value ? t('drag.enable') : t('drag.locked')}
</NTag>
</RDraggableCard>
)}
</DemoPage>
)
},
})

View File

@ -12,6 +12,6 @@
& .chart--container {
width: 100%;
height: 500px;
height: clamp(300px, 55vh, 500px);
}
}

View File

@ -1,3 +1,5 @@
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import './index.scss'
import { RChart, useChart } from '@/components'
import type { RChartType } from '@/components'
@ -23,6 +25,9 @@ const Echart = defineComponent({
const state = reactive({
loading: false,
loading1: false,
lineVisible: true,
barVisible: true,
revision: 1,
})
const baseOptions: GlobalEChartsCoreOption = {
@ -209,6 +214,7 @@ const Echart = defineComponent({
const mountChart = () => {
if (isDisposed()) {
render()
state.lineVisible = true
} else {
window.$message.warning('图表已渲染~')
}
@ -216,6 +222,7 @@ const Echart = defineComponent({
const unmountChart = () => {
dispose()
state.lineVisible = false
}
const updateChartOptions = () => {
@ -232,6 +239,7 @@ const Echart = defineComponent({
.map(() => createData())
state.loading1 = false
state.revision += 1
}, 1000)
}
@ -259,97 +267,124 @@ const Echart = defineComponent({
this
return (
<div class="echart">
<NCard title="chart 组件">
<h3>该组件基于 ECharts, Vueuse 封装。默认做了最佳的优化封装实践。</h3>
<h3>
开箱即用的优化策略:节流更新图表、异步渲染、自动销毁、贴花、加载、主题、视窗区域渲染、自动更新尺寸等高级特性。
</h3>
</NCard>
<NCard title="预设 card 风格图表">
<NFlex style={['padding: 18px 0']}>
<NButton onClick={this.mountChart.bind(this)}>渲染</NButton>
<NButton onClick={this.unmountChart.bind(this)}>卸载</NButton>
<NButton onClick={this.updateChartOptions.bind(this)}>
更新配置项
</NButton>
<NButton
onClick={() => {
this.loading1 = !this.loading1
}}
>
{`${this.loading1 ? '关闭' : '开启'}`}加载动画
</NButton>
</NFlex>
<div class="chart--container">
<RChart
onRegister={register}
title="周销售量"
autoChangeTheme
options={this.baseLineOptions}
showAria={this.chartAria}
preset="card"
loading={loading1}
/>
</div>
</NCard>
<NCard title="不跟随主题切换的暗色主题可视化图,并且手动指定原始主题色">
<NFlex vertical>
<NFlex>
<DemoPage
title={this.$t('menu.Echart')}
description={this.$t('showcase.chartDescription')}
eyebrow="RAY TEMPLATE / EXAMPLES"
>
<div class="echart">
<NCard title={this.$t('demoDetails.chart.sales')}>
<NFlex style={['padding: 18px 0']}>
<NButton disabled={this.lineVisible} onClick={this.mountChart}>
{this.$t('demoDetails.chart.mount')}
</NButton>
<NButton disabled={!this.lineVisible} onClick={this.unmountChart}>
{this.$t('demoDetails.chart.dispose')}
</NButton>
<NButton
disabled={!this.lineVisible || loading1}
onClick={this.updateChartOptions}
>
{this.$t('demoDetails.chart.update')}
</NButton>
<NButton
onClick={() => {
if (isDisposed2()) {
render2()
} else {
window.$message.warning('不可以重复渲染图表~')
}
this.loading1 = !this.loading1
}}
>
渲染
{this.$t(
loading1
? 'demoDetails.chart.stopLoading'
: 'demoDetails.chart.showLoading',
)}
</NButton>
<NButton onClick={dispose2.bind(this)}>卸载</NButton>
</NFlex>
<div class="chart--container">
<RChart
onRegister={register2}
autoChangeTheme={false}
theme="default"
options={this.baseOptions}
onRegister={register}
title={this.$t('demoDetails.chart.sales')}
autoChangeTheme
options={this.baseLineOptions}
showAria={this.chartAria}
preset="card"
loading={loading1}
/>
</div>
</NFlex>
</NCard>
<NCard title="加载动画">
<NSwitch
v-model:value={this.chartLoading}
onUpdateValue={this.handleLoadingShow.bind(this)}
style={['padding: 18px 0']}
>
{{
checked: () => '隐藏加载动画',
unchecked: () => '显示加载动画',
}}
</NSwitch>
<div class="chart--container">
<RChart loading={this.loading} options={this.baseOptions} />
</div>
</NCard>
<NCard title="贴画可视化图">
<NSwitch
v-model:value={this.chartAria}
onUpdateValue={this.handleAriaShow.bind(this)}
style={['padding: 18px 0']}
>
{{
checked: () => '隐藏贴花',
unchecked: () => '显示贴花',
}}
</NSwitch>
<div class="chart--container">
<RChart options={this.baseOptions} showAria={this.chartAria} />
</div>
</NCard>
</div>
<DemoResult label={this.$t('demoDetails.chart.series')}>
{this.lineVisible
? this.$t('demoDetails.chart.revision', {
value: this.revision,
})
: this.$t('demoDetails.chart.unmounted')}
</DemoResult>
</NCard>
<NCard title={this.$t('demoDetails.chart.fixedTheme')}>
<NFlex vertical>
<NFlex>
<NButton
onClick={() => {
if (isDisposed2()) {
render2()
this.barVisible = true
} else {
window.$message.warning('不可以重复渲染图表~')
}
}}
>
{this.$t('demoDetails.chart.mount')}
</NButton>
<NButton
disabled={!this.barVisible}
onClick={() => {
dispose2()
this.barVisible = false
}}
>
{this.$t('demoDetails.chart.dispose')}
</NButton>
</NFlex>
<div class="chart--container">
<RChart
onRegister={register2}
autoChangeTheme={false}
theme="default"
options={this.baseOptions}
/>
</div>
</NFlex>
</NCard>
<NCard title={this.$t('demoDetails.chart.showLoading')}>
<NSwitch
v-model:value={this.chartLoading}
onUpdateValue={this.handleLoadingShow.bind(this)}
style={['padding: 18px 0']}
>
{{
checked: () => this.$t('demoDetails.chart.stopLoading'),
unchecked: () => this.$t('demoDetails.chart.showLoading'),
}}
</NSwitch>
<div class="chart--container">
<RChart loading={this.loading} options={this.baseOptions} />
</div>
</NCard>
<NCard title={this.$t('demoDetails.chart.pattern')}>
<NSwitch
v-model:value={this.chartAria}
onUpdateValue={this.handleAriaShow.bind(this)}
style={['padding: 18px 0']}
>
{{
checked: () => this.$t('demoDetails.chart.hidePattern'),
unchecked: () => this.$t('demoDetails.chart.pattern'),
}}
</NSwitch>
<div class="chart--container">
<RChart options={this.baseOptions} showAria={this.chartAria} />
</div>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -1,86 +1,97 @@
import { RFlow, RForm, useFlow } from '@/components'
import type { FlowGraphData } from '@/components'
import { NCard, NFlex, NFormItemGridItem, NGrid, NSwitch } from 'naive-ui'
import { RFlow, useFlow } from '@/components'
import { useI18n } from '@/hooks'
import { NButton, NCard, NFlex, NSwitch, NTag } from 'naive-ui'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'
export default defineComponent({
name: 'RFlowDemo',
setup() {
const { t } = useI18n('demoDetails')
const [register, { getFlowInstance }] = useFlow()
const flowDataRef = ref<FlowGraphData>()
const settingRef = ref({
readonly: false,
const readonlyMode = ref(false)
const canvasKey = ref(0)
const ready = ref(false)
const output = ref('')
const graph = () => ({
nodes: [
{ id: 'review', type: 'rect', x: 100, y: 105, text: t('flow.review') },
{ id: 'done', type: 'circle', x: 235, y: 215, text: t('flow.done') },
],
edges: [
{
id: 'review-to-done',
type: 'polyline',
sourceNodeId: 'review',
targetNodeId: 'done',
},
],
})
const getInst = () => {
console.log(getFlowInstance())
window.$message.info('获取实例成功,请在 console 中查看')
}
setTimeout(() => {
flowDataRef.value = {
// 节点
nodes: [
{
id: '21',
type: 'rect',
x: 300,
y: 100,
text: 'rect node',
},
{
id: '50',
type: 'circle',
x: 500,
y: 100,
text: 'circle node',
},
],
// 边
edges: [
{
id: '21',
type: 'polyline',
sourceNodeId: '50',
targetNodeId: '21',
},
],
}
}, 1000)
onMounted(() => {
getInst()
})
return {
register,
flowDataRef,
settingRef,
}
},
render() {
const { register, flowDataRef, settingRef } = this
return (
<NFlex vertical>
<NCard>
<RForm>
<NGrid xGap={4} yGap={18} cols={4}>
<NFormItemGridItem label="禁用流程图">
<NSwitch v-model:value={settingRef.readonly} />
</NFormItemGridItem>
</NGrid>
</RForm>
return () => (
<DemoPage title={t('flow.title')} description={t('flow.intro')}>
<NCard title={t('flow.canvas')}>
<div class="r-demo-card-stack">
<NFlex align="center">
<NSwitch
v-model:value={readonlyMode.value}
aria-label={t('flow.readonly')}
/>
<NTag bordered={false}>
{readonlyMode.value ? t('flow.readonly') : t('flow.editable')}
</NTag>
<NButton
disabled={!ready.value}
onClick={() => getFlowInstance().fitView(24, 24)}
>
{t('flow.fit')}
</NButton>
<NButton
disabled={!ready.value}
onClick={() => {
ready.value = false
output.value = ''
canvasKey.value += 1
}}
>
{t('flow.reset')}
</NButton>
<NButton
type="primary"
secondary
disabled={!ready.value}
onClick={() => {
output.value = JSON.stringify(
getFlowInstance().getGraphData(),
null,
2,
)
}}
>
{t('flow.inspect')}
</NButton>
</NFlex>
<div class="r-demo-flow-canvas">
<RFlow
key={canvasKey.value}
height={320}
readonly={readonlyMode.value}
onRegister={(flow) => {
register(flow)
flow.render(graph())
flow.fitView(24, 24)
ready.value = true
}}
/>
</div>
{output.value && (
<DemoResult label={t('flow.graph')}>
<pre>{output.value}</pre>
</DemoResult>
)}
</div>
</NCard>
<NCard>
<RFlow
height={500}
onRegister={register}
data={flowDataRef}
readonly={settingRef.readonly}
/>
</NCard>
</NFlex>
</DemoPage>
)
},
})

View File

@ -1,5 +1,5 @@
import { useHookPlusRequest } from '@/axios'
import { RForm, useForm } from '@/components'
import { useI18n } from '@/hooks'
import {
NButton,
NCard,
@ -11,186 +11,201 @@ import {
NInputNumber,
NRadio,
NRadioGroup,
NSwitch,
NText,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
interface FormModel {
name: string | null
age: number | null
gender: string | null
date: Date | null
date: number | null
remark: string | null
}
export default defineComponent({
name: 'RFormDemo',
setup() {
// 使用以下 hooks 的时候,应该注意调用时机
const { t } = useI18n('demoDetails')
const rules = computed(() => ({
name: {
required: true,
message: t('form.nameRequired'),
trigger: ['blur', 'change'],
key: 'name',
},
age: {
required: true,
message: t('form.ageRequired'),
trigger: ['blur', 'change'],
type: 'number' as const,
min: 0,
max: 120,
},
date: {
required: true,
message: t('form.dateRequired'),
trigger: ['blur', 'change'],
type: 'number' as const,
},
gender: {
required: true,
message: t('form.genderRequired'),
trigger: 'change',
},
}))
const [
register,
{
validate,
restoreValidation,
formRules,
reset,
validateTargetField,
formConditionRef,
reset,
formConditionRef: model,
},
] = useForm<FormModel>(
{
name: null,
age: null,
gender: null,
date: null,
remark: null,
},
{
name: {
required: true,
message: '请输入姓名',
trigger: ['blur', 'change'],
key: 'name',
},
date: {
required: true,
message: '请选择日期',
trigger: ['blur', 'change'],
type: 'number',
},
gender: {
required: true,
message: '请选择性别',
trigger: 'change',
},
age: {
required: true,
message: '请输入年龄',
trigger: ['blur', 'change'],
type: 'number',
},
},
)
] = useForm<FormModel>({
name: null,
age: null,
gender: null,
date: null,
remark: null,
})
const ids = { name: useId(), age: useId(), remark: useId() }
const submission = ref<string>()
const status = ref('form.waiting')
const formLoading = ref(false)
const submit = async (event: Event) => {
event.preventDefault()
const { run: runHookPlusRequest } = useHookPlusRequest(
() => {
return new Promise((resolve, reject) => {
validate()
.then(() => {
formLoading.value = true
setTimeout(() => {
window.$message.success('校验成功')
resolve(true)
}, 500)
})
.catch(reject)
.finally(() => {
formLoading.value = false
})
})
},
{
manual: true,
},
)
return {
register,
formConditionRef,
restoreValidation,
validate,
formRules,
validateTargetField,
reset,
formLoading,
runHookPlusRequest,
try {
await validate()
submission.value = JSON.stringify(model.value, null, 2)
status.value = 'form.submitted'
} catch {
submission.value = void 0
status.value = 'form.invalid'
}
}
},
render() {
const { formConditionRef } = this
const {
register,
restoreValidation,
formRules,
validateTargetField,
reset,
runHookPlusRequest,
} = this
return (
<NCard
title={() => (
<NFlex align="center">
<NText>useForm 表单校验</NText>
<NSwitch v-model:value={this.formLoading} />
</NFlex>
)}
>
{{
default: () => (
return () => (
<DemoPage title={t('form.title')} description={t('form.intro')}>
<div class="r-demo-grid">
<NCard title={t('form.profile')}>
<RForm
model={model.value}
rules={rules.value}
onRegister={register}
rules={formRules()}
model={formConditionRef}
submitWhenEnter
onFinish={() => {
window.$message.success('表单提交成功')
}}
loading={this.formLoading}
onSubmit={submit}
>
<NGrid cols={24} xGap={24}>
<NFormItemGi label="姓名" path="name" span={12}>
<NInput v-model:value={formConditionRef.name} />
</NFormItemGi>
<NFormItemGi label="年龄" path="age" span={12}>
<NInputNumber
v-model:value={formConditionRef.age}
showButton={false}
<NGrid cols="1 480:2" responsive="self" xGap={16}>
<NFormItemGi
label={t('form.name')}
labelProps={{ for: ids.name }}
path="name"
>
<NInput
v-model:value={model.value.name}
inputProps={{ id: ids.name }}
/>
</NFormItemGi>
<NFormItemGi label="出生日期" path="date" span={12}>
<NDatePicker v-model:value={formConditionRef.date} />
<NFormItemGi
label={t('form.age')}
labelProps={{ for: ids.age }}
path="age"
>
<NInputNumber
v-model:value={model.value.age}
inputProps={{ id: ids.age }}
min={0}
max={120}
/>
</NFormItemGi>
<NFormItemGi label="性别" path="gender" span={12}>
<NRadioGroup v-model:value={formConditionRef.gender}>
<NRadio value="girl">女</NRadio>
<NRadio value="man">男</NRadio>
<NFormItemGi label={t('form.date')} path="date">
<NDatePicker v-model:value={model.value.date} type="date" />
</NFormItemGi>
<NFormItemGi label={t('form.gender')} path="gender">
<NRadioGroup
v-model:value={model.value.gender}
aria-label={t('form.gender')}
>
<NRadio value="female">{t('form.female')}</NRadio>
<NRadio value="male">{t('form.male')}</NRadio>
</NRadioGroup>
</NFormItemGi>
<NFormItemGi label="备注信息" span={24}>
<NFormItemGi
label={t('form.notes')}
labelProps={{ for: ids.remark }}
span={2}
>
<NInput
type="textarea"
v-model:value={formConditionRef.remark}
v-model:value={model.value.remark}
inputProps={{ id: ids.remark }}
/>
</NFormItemGi>
<NFormItemGi span={24}>
<NFlex>
<NButton type="info" onClick={() => reset()}>
重置表单为初始状态
</NButton>
<NButton type="warning" onClick={restoreValidation}>
移除校验状态
</NButton>
<NButton
type="primary"
onClick={() => validateTargetField('name')}
>
仅校验姓名字段
</NButton>
<NButton type="primary" onClick={runHookPlusRequest}>
校验
</NButton>
</NFlex>
</NFormItemGi>
</NGrid>
<NFlex>
<NButton type="primary" attrType="submit">
{t('form.submit')}
</NButton>
<NButton
onClick={() => {
reset({
name: 'Ray',
age: 28,
gender: 'female',
date: new Date(1998, 6, 12).getTime(),
remark: null,
})
submission.value = void 0
status.value = 'form.waiting'
}}
>
{t('form.sample')}
</NButton>
<NButton
onClick={() => {
void validateTargetField('name')
.then(() => {
status.value = 'form.nameValid'
})
.catch(() => {
status.value = 'form.nameRequired'
})
}}
>
{t('form.validateName')}
</NButton>
<NButton
onClick={() => {
restoreValidation()
status.value = 'form.waiting'
}}
>
{t('form.clear')}
</NButton>
<NButton
onClick={() => {
reset()
submission.value = void 0
status.value = 'form.waiting'
}}
>
{t('form.reset')}
</NButton>
</NFlex>
</RForm>
),
'header-extra': () => '输入表单的时候,试试按下 Enter 键',
}}
</NCard>
</NCard>
<NCard title={t('form.payload')}>
<DemoResult
label={t(status.value)}
error={status.value === 'form.invalid'}
>
<pre>{submission.value ?? t('empty')}</pre>
</DemoResult>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -1,31 +1,59 @@
import { RIframe } from '@/components'
import { NCard, NFlex } from 'naive-ui'
import { useI18n } from '@/hooks'
import { NButton, NCard, NTag } from 'naive-ui'
import DemoPage from '../components/DemoPage'
const IframeDemo = defineComponent({
export default defineComponent({
name: 'IframeDemo',
setup() {
return {}
},
render() {
return (
<NFlex vertical size={[20, 20]}>
<NCard title="naive ui(延迟加载)">
<RIframe
src="https://www.naiveui.com/zh-CN/dark"
height="300"
allow="fullscreen"
/>
</NCard>
<NCard title="vue-hooks-plus(立即加载)">
<RIframe
src="https://inhiblabcore.github.io/docs/hooks/"
height="300"
lazy={false}
/>
</NCard>
</NFlex>
const { t } = useI18n('demoDetails')
const lazyMounted = ref(false)
const loaded = reactive({ eager: false, lazy: false })
const source = `${import.meta.env.BASE_URL}examples/embed.html`
return () => (
<DemoPage title={t('iframe.title')} description={t('iframe.intro')}>
<div class="r-demo-grid">
{(['eager', 'lazy'] as const).map((mode) => (
<NCard key={mode} title={t(`iframe.${mode}`)}>
{{
'header-extra': () => (
<NTag
size="small"
bordered={false}
type={loaded[mode] ? 'success' : 'default'}
>
{loaded[mode] ? t('iframe.loaded') : t('iframe.pending')}
</NTag>
),
default: () =>
mode === 'eager' || lazyMounted.value ? (
<RIframe
src={source}
title={t(`iframe.${mode}`)}
height={220}
lazy={mode === 'lazy'}
onSuccess={() => {
loaded[mode] = true
}}
/>
) : (
<div class="r-demo-stage">
<NButton
secondary
onClick={() => {
lazyMounted.value = true
}}
>
{t('iframe.mount')}
</NButton>
</div>
),
}}
</NCard>
))}
</div>
</DemoPage>
)
},
})
export default IframeDemo

View File

@ -1,113 +1,113 @@
import { RModal, useModal } from '@/components'
import { NButton, NCard, NFlex } from 'naive-ui'
import { useI18n } from '@/hooks'
import { NButton, NCard, NFlex, NInputNumber, NTag } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
const variants = ['card', 'dialog', 'fullscreen'] as const
export default defineComponent({
name: 'ModalDemo',
setup() {
const state = reactive({
modal1: false,
modal2: false,
modal3: false,
})
const { t } = useI18n('demoDetails')
const variant = ref<(typeof variants)[number]>('card')
const visible = ref(false)
const width = ref<number | null>(480)
const last = ref<string>()
const { create } = useModal()
const createCardModal = () => {
create({
title: '卡片模态框',
draggable: true,
preset: 'card',
content: () => (
<div style="height: 3000px;">我可以被拖拽的全屏card模态框</div>
),
fullscreen: true,
})
const open = (mode: (typeof variants)[number]) => {
variant.value = mode
visible.value = true
}
const content = () => (
<DemoResult label={t('modal.record')}>
<strong>RAY-024</strong>
</DemoResult>
)
const createDialogModal = () => {
create({
title: '模态框',
content: '内容',
preset: 'dialog',
draggable: true,
})
}
return () => (
<DemoPage title={t('modal.title')} description={t('modal.intro')}>
<div class="r-demo-grid">
{variants.map((mode) => (
<NCard key={mode} title={t(`modal.${mode}`)}>
<div class="r-demo-card-stack">
<div
class={[
'r-demo-modal-sketch',
`r-demo-modal-sketch--${mode}`,
]}
aria-hidden="true"
>
<span />
</div>
<NButton type="primary" secondary onClick={() => open(mode)}>
{t(`modal.open.${mode}`)}
</NButton>
</div>
</NCard>
))}
<NCard title={t('modal.width')}>
<div class="r-demo-card-stack">
<NFlex align="center">
<NInputNumber
v-model:value={width.value}
min={280}
max={960}
step={40}
aria-label={t('modal.width')}
/>
<NTag bordered={false}>px</NTag>
</NFlex>
<NButton onClick={() => open('card')}>
{t('modal.applyWidth')}
</NButton>
</div>
</NCard>
<NCard class="r-demo-grid__wide" title="useModal">
<NFlex align="center">
<NButton
onClick={() =>
create({ preset: 'card', title: t('modal.card'), content })
}
>
{t('modal.createCard')}
</NButton>
<NButton
onClick={() =>
create({
preset: 'dialog',
title: t('modal.dialog'),
content,
})
}
>
{t('modal.createDialog')}
</NButton>
</NFlex>
</NCard>
</div>
return {
...toRefs(state),
createCardModal,
createDialogModal,
}
},
render() {
const { createCardModal, createDialogModal } = this
<DemoResult label={t('modal.last')}>
{last.value ? t(`modal.${last.value}`) : t('empty')}
</DemoResult>
return (
<NFlex vertical>
<NCard title="props">
<NFlex vertical>
<h3>fullscreen: 全屏模态框。</h3>
</NFlex>
</NCard>
<RModal
v-model:show={this.modal1}
title="全屏模态框"
fullscreen
preset="card"
v-model:show={visible.value}
preset={variant.value === 'dialog' ? 'dialog' : 'card'}
title={t(`modal.${variant.value}`)}
fullscreen={variant.value === 'fullscreen'}
draggable={variant.value !== 'fullscreen'}
cardWidth={`min(${width.value ?? 480}px, calc(100vw - 32px))`}
dialogWidth="min(380px, calc(100vw - 32px))"
closable
onAfterLeave={() => {
last.value = variant.value
}}
>
<div style="height: 3000px;">我可以被拖拽的全屏card模态框</div>
{content()}
</RModal>
<RModal
v-model:show={this.modal2}
preset="card"
title="可拖拽卡片模态框"
draggable
>
<p>我可以被拖拽</p>
</RModal>
<RModal
v-model:show={this.modal3}
preset="dialog"
title="可拖拽卡片模态框"
draggable
>
<p>我可以被拖拽</p>
</RModal>
<NCard title="可拖拽模态框">
<NButton onClick={() => (this.modal2 = true)}>卡片模态框</NButton>
<NButton onClick={() => (this.modal3 = true)}>对话框模态框</NButton>
</NCard>
<NCard title="全屏模态框">
<NFlex vertical>
<h4>
全屏模态框需要同时设置:fullscreen 为 true,并且 preset 为 card
时才会生效。
</h4>
<NButton onClick={() => (this.modal1 = true)}>打开</NButton>
</NFlex>
</NCard>
<NCard title="手动设置宽度">
<h4>
width(--r-modal-width): 当 preset 不为 dialog 或者 card
的时候,你可能用得上。
</h4>
<h4>
dialogWidth(--r-modal-dialog-width): 当 preset 为
dialog,你可能用得上。
</h4>
<h4>
cardWidth(--r-modal-card-width): 当 preset 为 card,你可能用得上。
</h4>
<h4>
所有的宽度配置属性都会注入一个对应的 `css variable`,有时候会用上。
</h4>
</NCard>
<NCard title="重写 useModal">
<NButton onClick={createCardModal.bind(this)}>创建卡片模态框</NButton>
<NButton onClick={createDialogModal.bind(this)}>
创建对话框模态框
</NButton>
</NCard>
</NFlex>
</DemoPage>
)
},
})

View File

@ -1,22 +1,13 @@
import { NInput } from 'naive-ui'
import CacheRouteExample from '../../../components/CacheRouteExample'
const MultiMenuOne = defineComponent({
export default defineComponent({
name: 'MultiMenuOne',
setup() {
const inputValue = ref(null)
return {
inputValue,
}
},
render() {
return (
<div>
多级菜单-1
<NInput v-model={this.inputValue} />
</div>
<CacheRouteExample
title={this.$t('showcase.multiOneTitle')}
description={this.$t('showcase.multiOneDescription')}
/>
)
},
})
export default MultiMenuOne

View File

@ -1,22 +1,13 @@
import { NInput } from 'naive-ui'
import CacheRouteExample from '../../../../../components/CacheRouteExample'
const SubMenuOther = defineComponent({
export default defineComponent({
name: 'SubMenuOther',
setup() {
const inputValue = ref(null)
return {
inputValue,
}
},
render() {
return (
<div>
多级菜单-2-1
<NInput v-model={this.inputValue} />
</div>
<CacheRouteExample
title={this.$t('showcase.multiOtherTitle')}
description={this.$t('showcase.multiOtherDescription')}
/>
)
},
})
export default SubMenuOther

View File

@ -1,26 +1,13 @@
import { NInput } from 'naive-ui'
import CacheRouteExample from '../../../../../../../components/CacheRouteExample'
const MultiMenuTwoOne = defineComponent({
export default defineComponent({
name: 'MultiMenuTwoOne',
setup() {
const inputValue = ref(null)
return {
inputValue,
}
},
render() {
return (
<div
style={{
height: 'var(--layout-content-height)',
}}
>
多级菜单2-2-1
<NInput v-model={this.inputValue} />
</div>
<CacheRouteExample
title={this.$t('showcase.multiNestedTitle')}
description={this.$t('showcase.multiNestedDescription')}
/>
)
},
})
export default MultiMenuTwoOne

View File

@ -1,149 +1,107 @@
import { useI18n } from '@/hooks'
import { add, distribute, divide, format, multiply, subtract } from '@/utils'
import { NCard, NDynamicTags, NFlex, NInputNumber, NLayout } from 'naive-ui'
import {
NCard,
NDynamicTags,
NFormItem,
NGrid,
NGridItem,
NInputNumber,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
const CalculatePrecision = defineComponent({
const operations = { add, subtract, multiply, divide }
export default defineComponent({
name: 'CalculatePrecision',
setup() {
const state = reactive({
addOptions: ['1', '0.2', '0.1', '1.1'],
subtractOptions: ['1', '0.2', '0.1', '1.1'],
multiplyOptions: ['1', '0.2', '0.1', '1.1'],
divideOptions: ['1', '0.2', '0.1', '1.1'],
distributeValue: 12,
distributeOutputValue: [] as unknown[],
distributeLength: 3,
const { t } = useI18n('demoDetails')
const operands = reactive({
add: ['0.1', '0.2'],
subtract: ['1', '0.7'],
multiply: ['0.1', '0.2'],
divide: ['1', '3'],
})
const actionMap = {
addOptions: add,
subtractOptions: subtract,
multiplyOptions: multiply,
divideOptions: divide,
}
const amount = ref<number | null>(10)
const parts = ref<number | null>(3)
const allocation = computed(() =>
amount.value === null || parts.value === null
? []
: distribute(amount.value, parts.value),
)
const copilotFunc = (value: string[], path: keyof typeof actionMap) => {
const action = actionMap[path]
const result = action(...value)
return () => (
<DemoPage title={t('precision.title')} description={t('precision.intro')}>
<div class="r-demo-grid">
{(Object.keys(operations) as (keyof typeof operations)[]).map(
(operation) => {
const values = operands[operation]
const invalid =
!values.length ||
values.some(
(value) => !/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(value),
)
const zeroDivisor =
operation === 'divide' &&
values.slice(1).some((value) => Number(value) === 0)
let result = t('precision.invalid')
return '结果: ' + format(result)
}
if (!invalid && !zeroDivisor) {
try {
result = String(format(operations[operation](...values)))
} catch {
result = t('precision.invalid')
}
}
const updateDistributeValue = () => {
nextTick().then(() => {
state.distributeOutputValue = distribute(
state.distributeValue,
state.distributeLength,
)
})
}
updateDistributeValue()
return {
...toRefs(state),
copilotFunc,
updateDistributeValue,
}
},
render() {
return (
<NLayout>
<h2 style="margin: 0 0 20px 0">
计算方法,默认都保留八位小数与四舍五入,可以根据 format 方法自行转换
</h2>
<h3 style="margin: 0 0 20px 0">
示例方法都基于 currency.js
封装,利用其精度处理能力封装了常用的一些计算方法,解决精度问题。如果需要其他的方法请阅读官方文档
https://currency.js.org/#subtract
</h3>
<NFlex vertical>
<NCard title="加法">
{{
default: () => (
<NDynamicTags
v-model:value={this.addOptions}
onUpdateValue={(value: string[]) => {
this.copilotFunc(value, 'addOptions')
}}
/>
),
footer: () => {
return this.copilotFunc(this.addOptions, 'addOptions')
},
}}
return (
<NCard key={operation} title={t(`precision.${operation}`)}>
<div class="r-demo-card-stack">
<NDynamicTags v-model:value={operands[operation]} />
<DemoResult
label={t('result')}
error={invalid || zeroDivisor}
>
<strong>
{zeroDivisor ? t('precision.zero') : result}
</strong>
</DemoResult>
</div>
</NCard>
)
},
)}
<NCard class="r-demo-grid__wide" title={t('precision.allocation')}>
<div class="r-demo-card-stack">
<NGrid cols="1 480:2" responsive="self" xGap={16}>
<NGridItem>
<NFormItem label={t('precision.amount')} showFeedback={false}>
<NInputNumber v-model:value={amount.value} />
</NFormItem>
</NGridItem>
<NGridItem>
<NFormItem label={t('precision.parts')} showFeedback={false}>
<NInputNumber
v-model:value={parts.value}
min={1}
max={12}
precision={0}
/>
</NFormItem>
</NGridItem>
</NGrid>
<DemoResult label={t('result')}>
<code>
{allocation.value.length
? allocation.value.join(' + ')
: t('empty')}
</code>
</DemoResult>
</div>
</NCard>
<NCard title="减法">
{{
default: () => (
<NDynamicTags
v-model:value={this.subtractOptions}
onUpdateValue={(value: string[]) => {
this.copilotFunc(value, 'subtractOptions')
}}
/>
),
footer: () => {
return this.copilotFunc(this.subtractOptions, 'subtractOptions')
},
}}
</NCard>
<NCard title="乘法">
{{
default: () => (
<NDynamicTags
v-model:value={this.multiplyOptions}
onUpdateValue={(value: string[]) => {
this.copilotFunc(value, 'multiplyOptions')
}}
/>
),
footer: () => {
return this.copilotFunc(this.multiplyOptions, 'multiplyOptions')
},
}}
</NCard>
<NCard title="除法(非取模)">
{{
default: () => (
<NDynamicTags
v-model:value={this.divideOptions}
onUpdateValue={(value: string[]) => {
this.copilotFunc(value, 'divideOptions')
}}
/>
),
footer: () => {
return this.copilotFunc(this.divideOptions, 'divideOptions')
},
}}
</NCard>
<NCard title="平分一个值">
{{
default: () => (
<NFlex>
<NInputNumber
v-model:value={this.distributeValue}
onUpdateValue={() => {
this.updateDistributeValue()
}}
/>
<NInputNumber
v-model:value={this.distributeLength}
onUpdateValue={() => {
this.updateDistributeValue()
}}
/>
</NFlex>
),
footer: () => {
return '结果: ' + this.distributeOutputValue.join(', ')
},
}}
</NCard>
</NFlex>
</NLayout>
</div>
</DemoPage>
)
},
})
export default CalculatePrecision

View File

@ -1,95 +1,130 @@
import LOGO from '@/assets/images/ray.svg'
import { NButton, NCard, NFlex } from 'naive-ui'
import { useI18n } from '@/hooks'
import {
NButton,
NCard,
NFlex,
NFormItem,
NInput,
NRadioButton,
NRadioGroup,
NSwitch,
} from 'naive-ui'
import { Vue3NextQrcode } from 'vue3-next-qrcode'
import type { QRCodeInst, QRCodeStatus } from 'vue3-next-qrcode'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
const initial = 'https://xiaodaigua-ray.github.io/ray-template/'
export default defineComponent({
name: 'RQRCodeDemo',
setup() {
const qrcodeText = ref('ray template yes')
const qrcodeStatus = ref<QRCodeStatus | undefined>()
const rayQRCodeRef = ref<QRCodeInst>()
const { t } = useI18n('demoDetails')
const text = ref(initial)
const brand = ref(true)
const animated = ref(false)
const status = ref<'ready' | QRCodeStatus>('ready')
const rendered = ref(false)
const failed = ref(false)
const instance = useTemplateRef<QRCodeInst>('qrcode')
const id = useId()
return {
qrcodeText,
qrcodeStatus,
rayQRCodeRef,
}
},
render() {
return (
<NFlex>
<NCard>
<h2>
基于 awesome-qr 进行封装,支持 LOGO、gif、backgroundImage 等属性。
</h2>
<h2>该组件会自动监听文本内容变化,然后重新渲染(watchText)</h2>
<h2>具体使用请参考 props 配置项</h2>
</NCard>
<NCard title="基础二维码">
<NFlex>
<Vue3NextQrcode text="ray template yes" />
<Vue3NextQrcode text="ray template yes" logoImage={LOGO} />
<Vue3NextQrcode
text="ray template yes"
gifBackgroundURL="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80"
dotScale={0.5}
colorDark="#64d9d6"
/>
</NFlex>
</NCard>
<NCard title="状态二维码">
<NFlex>
<Vue3NextQrcode
text="ray template yes"
logoImage={LOGO}
status="error"
onReload={() => {
window.$message.info('reload event')
}}
/>
<Vue3NextQrcode
text="ray template yes"
logoImage={LOGO}
status="loading"
/>
</NFlex>
</NCard>
<NCard title="监听内容变化">
<NFlex vertical>
<NFlex>
<NButton
onClick={() => {
this.qrcodeStatus = 'loading'
watch([text, brand, animated], () => {
rendered.value = false
failed.value = false
})
setTimeout(() => {
this.qrcodeText = 'text updated: ' + new Date().getTime()
this.qrcodeStatus = void 0
}, 1000)
}}
return () => (
<DemoPage title={t('qr.title')} description={t('qr.intro')}>
<div class="r-demo-grid">
<NCard title={t('qr.controls')}>
<div class="r-demo-card-stack">
<NFormItem
label={t('qr.content')}
labelProps={{ for: id }}
showFeedback={false}
>
更新二维码内容
</NButton>
<NInput
v-model:value={text.value}
maxlength={160}
showCount
inputProps={{ id }}
/>
</NFormItem>
<NFlex align="center">
<NSwitch
v-model:value={brand.value}
aria-label={t('qr.brand')}
/>
<span>{t('qr.brand')}</span>
<NSwitch
v-model:value={animated.value}
aria-label={t('qr.animated')}
/>
<span>{t('qr.animated')}</span>
</NFlex>
<NRadioGroup
v-model:value={status.value}
aria-label={t('qr.status')}
>
{(['ready', 'loading', 'error'] as const).map((state) => (
<NRadioButton key={state} value={state}>
{t(`qr.${state}`)}
</NRadioButton>
))}
</NRadioGroup>
<NButton
onClick={() => {
this.rayQRCodeRef?.downloadQRCode()
}}
type="primary"
disabled={
!rendered.value || failed.value || status.value !== 'ready'
}
onClick={() => instance.value?.downloadQRCode()}
>
下载二维码
{t('qr.download')}
</NButton>
</NFlex>
<NFlex>
<Vue3NextQrcode
text={this.qrcodeText}
status={this.qrcodeStatus}
logoImage={LOGO}
ref="rayQRCodeRef"
/>
当前二维码内容:{this.qrcodeText}
</NFlex>
</NFlex>
</NCard>
</NFlex>
</div>
</NCard>
<NCard title={t('qr.preview')}>
<div class="r-demo-card-stack">
<div class="r-demo-artifact">
{text.value.trim() && !failed.value ? (
<Vue3NextQrcode
ref="qrcode"
text={text.value}
size={180}
logoImage={brand.value ? LOGO : void 0}
logoScale={0.22}
gifBackgroundURL={
animated.value
? `${import.meta.env.BASE_URL}examples/qr-background.gif`
: void 0
}
dotScale={animated.value ? 0.9 : void 0}
status={status.value === 'ready' ? void 0 : status.value}
errorDescription={t('qr.expired')}
errorActionDescription={t('qr.reload')}
onReload={() => {
status.value = 'ready'
}}
onSuccess={() => {
rendered.value = true
}}
onError={() => {
failed.value = true
}}
/>
) : (
<span>{failed.value ? t('qr.failed') : t('qr.noText')}</span>
)}
</div>
<DemoResult label={t('qr.content')}>
<code>{text.value || t('empty')}</code>
</DemoResult>
</div>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -1,9 +1,27 @@
.rely-about {
& .n-card {
margin-top: 18px;
&__search {
inline-size: min(100%, 240px);
}
&:first-child {
margin-top: 0;
&__packages {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 235px), 1fr));
gap: 8px;
list-style: none;
margin: 0;
padding: 0;
li {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 10px;
border: 1px solid var(--r-line);
border-radius: 8px;
background: var(--r-surface-muted);
overflow-wrap: anywhere;
}
}
}

View File

@ -1,137 +1,97 @@
import './index.scss'
import { NCard, NDescriptions, NDescriptionsItem, NTag } from 'naive-ui'
interface RelyDataOptions {
name: string
relyVersion: string
relyAddress: string
}
interface TemplateOptions {
name: string
label: string
url?: string
}
import { useI18n } from '@/hooks'
import {
NButton,
NCard,
NFlex,
NInput,
NRadioButton,
NRadioGroup,
NTag,
} from 'naive-ui'
import DemoPage from '../../../components/DemoPage'
export default defineComponent({
name: 'RelyAbout',
setup() {
const { pkg } = __APP_CFG__
const { dependencies, devDependencies, name, version } = pkg
const { t } = useI18n('demoDetails')
const { dependencies, devDependencies, name, version } = __APP_CFG__.pkg
const groups = { runtime: dependencies, development: devDependencies }
const scope = ref<keyof typeof groups>('runtime')
const query = ref('')
const packages = computed(() =>
Object.entries(groups[scope.value]).filter(([pkg]) =>
pkg.toLowerCase().includes(query.value.trim().toLowerCase()),
),
)
const columns = [
{
title: '依赖名称',
key: 'name',
},
{
title: '依赖版本',
key: 'relyVersion',
},
{
title: '依赖地址',
key: 'relyAddress',
},
]
const dependenciesOptions = ref<RelyDataOptions[]>([])
const devDependenciesOptions = ref<RelyDataOptions[]>([])
const templateOptions = [
{
name: '项目名称',
label: name,
},
{
name: '版本信息',
label: version,
},
{
name: '项目地址',
label: 'GitHub',
url: 'https://github.com/XiaoDaiGua-Ray/ray-template',
},
]
const handleGetRelyData = () => {
const _arrayFrom = (obj: object) =>
Object.keys(obj).reduce((pre, curr) => {
pre.push({
name: curr,
relyVersion: obj[curr as keyof typeof obj],
relyAddress: '',
})
return pre
}, [] as RelyDataOptions[])
dependenciesOptions.value = _arrayFrom(dependencies)
devDependenciesOptions.value = _arrayFrom(devDependencies)
}
const handleTagClick = (item: TemplateOptions) => {
if (item.url) {
window.open(item.url)
}
}
onBeforeMount(() => {
handleGetRelyData()
})
return {
columns,
dependenciesOptions,
devDependenciesOptions,
templateOptions,
handleTagClick,
}
},
render() {
return (
<div class="rely-about">
<NCard title="关于项目">
ray template 是一个基于: tsx pinia vue3.x vite sass 的中后台解决方案.
项目干净与轻巧,
已经集成了很多项目中可能需要的搬砖工具可以让你快速起一个相关项目,
并且不需要剔除大量无用页面与组件.
</NCard>
<NCard title="项目信息">
<NDescriptions bordered labelPlacement="left">
{this.templateOptions.map((curr) => (
<NDescriptionsItem key={curr.name} label={curr.name}>
<NTag
bordered={false}
type="info"
{...{
onClick: this.handleTagClick.bind(this, curr),
}}
style={[curr.url ? 'cursor: pointer' : '']}
>
{curr.label}
</NTag>
</NDescriptionsItem>
))}
</NDescriptions>
</NCard>
<NCard title="生产依赖">
<NDescriptions bordered labelPlacement="left">
{this.dependenciesOptions.map((curr) => (
<NDescriptionsItem key={curr.name} label={curr.name}>
{curr.relyVersion}
</NDescriptionsItem>
))}
</NDescriptions>
</NCard>
<NCard title="开发依赖">
<NDescriptions bordered labelPlacement="left">
{this.devDependenciesOptions.map((curr) => (
<NDescriptionsItem key={curr.name} label={curr.name}>
{curr.relyVersion}
</NDescriptionsItem>
))}
</NDescriptions>
</NCard>
</div>
return () => (
<DemoPage title={t('about.title')} description={t('about.intro')}>
{{
actions: () => (
<NButton
tag="a"
{...{
href: 'https://github.com/XiaoDaiGua-Ray/ray-template',
target: '_blank',
rel: 'noreferrer',
}}
secondary
>
GitHub
</NButton>
),
default: () => (
<NCard title={name} class="rely-about">
{{
'header-extra': () => (
<NTag bordered={false} type="info">
v{version}
</NTag>
),
default: () => (
<div class="r-demo-card-stack">
<NFlex align="center" justify="space-between">
<NRadioGroup
v-model:value={scope.value}
aria-label={t('about.group')}
>
<NRadioButton value="runtime">
{t('about.runtime')}
</NRadioButton>
<NRadioButton value="development">
{t('about.development')}
</NRadioButton>
</NRadioGroup>
<NInput
class="rely-about__search"
v-model:value={query.value}
placeholder={t('about.search')}
inputProps={{ 'aria-label': t('about.search') }}
clearable
/>
</NFlex>
{packages.value.length ? (
<ul class="rely-about__packages">
{packages.value.map(([pkg, installed]) => (
<li key={pkg}>
<code>{pkg}</code>
<NTag size="small" bordered={false}>
{installed}
</NTag>
</li>
))}
</ul>
) : (
<p role="status">{t('about.noMatch')}</p>
)}
</div>
),
}}
</NCard>
),
}}
</DemoPage>
)
},
})

View File

@ -0,0 +1,8 @@
export const routeDemoPeople = Array.from({ length: 10 }, (_, index) => ({
key: index,
name: `张三${index}`,
address: 'New York No. 1 Lake Park',
phone: '010-121212',
}))
export type RouteDemoPerson = (typeof routeDemoPeople)[number]

View File

@ -1,33 +1,72 @@
import { NCard, NFlex } from 'naive-ui'
import { useI18n } from '@/hooks'
import {
NButton,
NCard,
NDescriptions,
NDescriptionsItem,
NTag,
} from 'naive-ui'
import DemoPage from '../../components/DemoPage'
import DemoResult from '../../components/DemoResult'
import { routeDemoPeople } from '../people'
const RouterDemoDetail = defineComponent({
export default defineComponent({
name: 'RouterDemoDetail',
setup() {
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const person = computed(() =>
routeDemoPeople.find(({ key, name }) =>
route.query.id == null
? route.query.name === name
: route.query.id === String(key),
),
)
return {
route,
}
},
render() {
const { route } = this
return (
<NFlex>
<NCard title={(route.query.name as string) || 'hello'}>
你好 {route.query.name}
</NCard>
<NCard title="平层路由详情页面">我是平层路由详情页面</NCard>
<NCard title="TIP">
<h2>1. 可以点击面包屑或者菜单返回到主页面</h2>
<h2>
2. 如果这个页面需要配置多个详情页面,只需将该路由所在的 children
中,将所需页面配置为 sameLevel 即可。
</h2>
</NCard>
</NFlex>
return () => (
<DemoPage
title={t('showcase.detailTitle')}
description={t('showcase.detailDescription')}
>
{{
actions: () => (
<NButton
onClick={() => router.push('/router-demo/router-demo-home')}
>
{t('demoDetails.detail.back')}
</NButton>
),
default: () => (
<div class="r-demo-grid">
<NCard title={person.value?.name ?? t('showcase.detailTitle')}>
{person.value ? (
<NDescriptions column={1} bordered>
<NDescriptionsItem label={t('demoDetails.detail.address')}>
{person.value.address}
</NDescriptionsItem>
<NDescriptionsItem label={t('demoDetails.detail.phone')}>
{person.value.phone}
</NDescriptionsItem>
</NDescriptions>
) : (
t('demoDetails.detail.missing')
)}
</NCard>
<NCard title={t('demoDetails.nested.route')}>
<div class="r-demo-card-stack">
<NTag type="info" bordered={false}>
sameLevel
</NTag>
<DemoResult label={t('demoDetails.detail.params')}>
<pre>{JSON.stringify(route.query, null, 2)}</pre>
</DemoResult>
</div>
</NCard>
</div>
),
}}
</DemoPage>
)
},
})
export default RouterDemoDetail

View File

@ -1,34 +1,31 @@
import { RTablePro } from '@/components'
import { useI18n } from '@/hooks'
import { NButton, NFlex } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
export interface RowData {
key: string | number
name: string
phone: string
address: string
}
import { routeDemoPeople } from '../people'
import type { RouteDemoPerson } from '../people'
const RouterDemoHome = defineComponent({
name: 'RouterDemoHome',
setup() {
const router = useRouter()
const { t } = useI18n('demoDetails')
const columns: Ref<DataTableColumns<RowData>> = ref([
const columns = computed<DataTableColumns<RouteDemoPerson>>(() => [
{
title: '姓名',
title: t('detail.name'),
key: 'name',
},
{
title: '地址',
title: t('detail.address'),
key: 'address',
},
{
title: '联系方式',
title: t('detail.phone'),
key: 'phone',
},
{
title: '操作',
title: t('detail.action'),
key: '',
render: (row) => {
return (
@ -41,31 +38,22 @@ const RouterDemoHome = defineComponent({
router.push({
path: '/router-demo/router-demo-detail',
query: {
id: String(row.key),
name: row.name,
},
})
}}
>
详情
{t('detail.open')}
</NButton>
</NFlex>
)
},
},
])
const dataSource: RowData[] = []
for (let i = 0; i < 10; i++) {
dataSource.push({
name: '张三' + i,
address: 'New York No. 1 Lake Park',
phone: '010-121212',
key: i,
})
}
return {
dataSource,
dataSource: routeDemoPeople,
columns,
}
},

View File

@ -1,4 +1,32 @@
.scroll-reveal {
width: 100%;
height: 100%;
display: grid;
gap: 20px;
.n-card {
min-block-size: 220px;
background: var(--r-surface-muted);
}
&__number {
color: var(--r-primary-text);
font-size: clamp(2rem, 7vw, 4rem);
font-variant-numeric: tabular-nums;
}
}
@supports (animation-timeline: view()) {
@media (prefers-reduced-motion: no-preference) {
.scroll-reveal .n-card {
animation: reveal-example linear both;
animation-timeline: view();
animation-range: entry 5% entry 85%;
}
}
}
@keyframes reveal-example {
from {
opacity: 0.35;
transform: translateY(20px);
}
}

View File

@ -1,18 +1,27 @@
import './index.scss'
import { NCard } from 'naive-ui'
import DemoPage from '../components/DemoPage'
const ScrollReveal = defineComponent({
export default defineComponent({
name: 'ScrollReveal',
render() {
return (
<div class="scroll-reveal">
<NCard title="提示">
RayScrollReveal组件有点问题, 暂时移除. 不能正常的实现滚动动画.
很是操蛋!!!
</NCard>
</div>
<DemoPage
title={this.$t('menu.scrollReveal')}
description={this.$t('showcase.scrollDescription')}
eyebrow="RAY TEMPLATE / EXAMPLES"
>
<div class="scroll-reveal">
{Array.from({ length: 6 }, (_, index) => (
<NCard key={index}>
<strong class="scroll-reveal__number">
{String(index + 1).padStart(2, '0')}
</strong>
<p>{this.$t('showcase.scrollCard', { index: index + 1 })}</p>
</NCard>
))}
</div>
</DemoPage>
)
},
})
export default ScrollReveal