Compare commits
98 Commits
504411f532
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4b0413e42 | ||
|
|
d1b2d981b5 | ||
|
|
54a5f96644 | ||
|
|
8ffbc10a4e | ||
|
|
7a24c6bfd0 | ||
|
|
5a7d56265c | ||
|
|
c7694df2cc | ||
|
|
7eb6a626ad | ||
|
|
8a28f8654c | ||
|
|
5ab82d4571 | ||
|
|
4ff3e92049 | ||
|
|
59379dff79 | ||
|
|
65fc29f777 | ||
|
|
faf4ea1155 | ||
|
|
c1d2958095 | ||
|
|
1ae0371c18 | ||
|
|
449cf1f6c7 | ||
|
|
0399e8ede4 | ||
|
|
e803ffa38c | ||
|
|
fd569657d5 | ||
|
|
e1750b16c4 | ||
|
|
a84f7c4906 | ||
|
|
4ea627c0c0 | ||
|
|
edebda89fc | ||
|
|
4d46a726f4 | ||
|
|
e713f3e92d | ||
|
|
62b8779535 | ||
|
|
386b2742b9 | ||
|
|
ad12dc8e9a | ||
|
|
a6c4e5e228 | ||
|
|
77f5b74cea | ||
|
|
2a775ab5e3 | ||
|
|
f53a3da87c | ||
|
|
dd7c8b4162 | ||
|
|
3d857002e0 | ||
|
|
830aca7088 | ||
|
|
cc18a19e7e | ||
|
|
7e863f00f1 | ||
|
|
5f848e6c78 | ||
|
|
6672fdcac3 | ||
|
|
3e371c16c7 | ||
|
|
a38f85bbf9 | ||
|
|
6d3e975f49 | ||
|
|
8d97b532ea | ||
|
|
78b85c9619 | ||
|
|
aba6d4c09e | ||
|
|
9d39a48117 | ||
|
|
903019b15a | ||
|
|
b670e06bc9 | ||
|
|
7a4477966d | ||
|
|
edb640a64b | ||
|
|
d67b18b60a | ||
|
|
2493bbcb2f | ||
|
|
3f19402c81 | ||
|
|
06e7739293 | ||
|
|
3d304ec8c9 | ||
|
|
bbde4c4a66 | ||
|
|
7e81a8ca59 | ||
|
|
4150739d27 | ||
|
|
569eb49228 | ||
|
|
a85f14e79c | ||
|
|
056a3cbfa9 | ||
|
|
f57ed1b712 | ||
|
|
8f83e48443 | ||
|
|
a6f3f2d144 | ||
|
|
ff80bef939 | ||
|
|
d38897018f | ||
|
|
74f7b638f4 | ||
|
|
d0d19792cf | ||
|
|
79ccddf705 | ||
|
|
95634bd82a | ||
|
|
607b5f8c91 | ||
|
|
1fffd93c83 | ||
|
|
ab264b54aa | ||
|
|
56197b13e7 | ||
|
|
1a6bd1174e | ||
|
|
311d90b93e | ||
|
|
95bd774bd1 | ||
|
|
1885a91994 | ||
|
|
14b661a3ac | ||
|
|
ab908b9315 | ||
|
|
1ea63c486e | ||
|
|
6eed913a82 | ||
|
|
10b5624dac | ||
|
|
61845e3662 | ||
|
|
02c68a1f9f | ||
|
|
b682631aa8 | ||
|
|
e6fcc43cb2 | ||
|
|
b5f3ce25dc | ||
|
|
65f06c21f5 | ||
|
|
cd9a217f92 | ||
|
|
95b7ce1ebe | ||
|
|
bdd7ed4023 | ||
|
|
f11cfe1bda | ||
|
|
f95b929968 | ||
|
|
e7fdf1eae1 | ||
|
|
689e10d3b3 | ||
|
|
08da3b171a |
5
.claude/skills/pinia/GENERATION.md
Normal file
5
.claude/skills/pinia/GENERATION.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Generation Info
|
||||
|
||||
- **Source:** `sources/pinia`
|
||||
- **Git SHA:** `55dbfc5c20d4461748996aa74d8c0913e89fb98e`
|
||||
- **Generated:** 2026-01-28
|
||||
21
.claude/skills/pinia/LICENSE.md
Normal file
21
.claude/skills/pinia/LICENSE.md
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025-PRESENT Anthony Fu <https://github.com/antfu>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
59
.claude/skills/pinia/SKILL.md
Normal file
59
.claude/skills/pinia/SKILL.md
Normal file
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: pinia
|
||||
description: Pinia official Vue state management library, type-safe and extensible. Use when defining stores, working with state/getters/actions, or implementing store patterns in Vue apps.
|
||||
metadata:
|
||||
author: Anthony Fu
|
||||
version: "2026.1.28"
|
||||
source: Generated from https://github.com/vuejs/pinia, scripts located at https://github.com/antfu/skills
|
||||
---
|
||||
|
||||
# Pinia
|
||||
|
||||
Pinia is the official state management library for Vue, designed to be intuitive and type-safe. It supports both Options API and Composition API styles, with first-class TypeScript support and devtools integration.
|
||||
|
||||
> The skill is based on Pinia v3.0.4, generated at 2026-01-28.
|
||||
|
||||
## Core References
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Stores | Defining stores, state, getters, actions, storeToRefs, subscriptions | [core-stores](references/core-stores.md) |
|
||||
|
||||
## Features
|
||||
|
||||
### Extensibility
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Plugins | Extend stores with custom properties, state, and behavior | [features-plugins](references/features-plugins.md) |
|
||||
|
||||
### Composability
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Composables | Using Vue composables within stores (VueUse, etc.) | [features-composables](references/features-composables.md) |
|
||||
| Composing Stores | Store-to-store communication, avoiding circular dependencies | [features-composing-stores](references/features-composing-stores.md) |
|
||||
|
||||
## Best Practices
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Testing | Unit testing with @pinia/testing, mocking, stubbing | [best-practices-testing](references/best-practices-testing.md) |
|
||||
| Outside Components | Using stores in navigation guards, plugins, middlewares | [best-practices-outside-component](references/best-practices-outside-component.md) |
|
||||
|
||||
## Advanced
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| SSR | Server-side rendering, state hydration | [advanced-ssr](references/advanced-ssr.md) |
|
||||
| Nuxt | Nuxt integration, auto-imports, SSR best practices | [advanced-nuxt](references/advanced-nuxt.md) |
|
||||
| HMR | Hot module replacement for development | [advanced-hmr](references/advanced-hmr.md) |
|
||||
|
||||
## Key Recommendations
|
||||
|
||||
- **Prefer Setup Stores** for complex logic, composables, and watchers
|
||||
- **Use `storeToRefs()`** when destructuring state/getters to preserve reactivity
|
||||
- **Actions can be destructured directly** - they're bound to the store
|
||||
- **Call stores inside functions** not at module scope, especially for SSR
|
||||
- **Add HMR support** to each store for better development experience
|
||||
- **Use `@pinia/testing`** for component tests with mocked stores
|
||||
5
.claude/skills/pinia/SYNC.md
Normal file
5
.claude/skills/pinia/SYNC.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Sync Info
|
||||
|
||||
- **Source:** `vendor/antfu/skills/pinia`
|
||||
- **Git SHA:** `4086f59fa12d308fb05592ca8ce1704fbb940aa3`
|
||||
- **Synced:** 2026-01-30
|
||||
61
.claude/skills/pinia/references/advanced-hmr.md
Normal file
61
.claude/skills/pinia/references/advanced-hmr.md
Normal file
@@ -0,0 +1,61 @@
|
||||
---
|
||||
name: hot-module-replacement
|
||||
description: Enable HMR to preserve store state during development
|
||||
---
|
||||
|
||||
# Hot Module Replacement (HMR)
|
||||
|
||||
Pinia supports HMR to edit stores without page reload, preserving existing state.
|
||||
|
||||
## Setup
|
||||
|
||||
Add this snippet after each store definition:
|
||||
|
||||
```ts
|
||||
import { defineStore, acceptHMRUpdate } from 'pinia'
|
||||
|
||||
export const useAuth = defineStore('auth', {
|
||||
// store options...
|
||||
})
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.accept(acceptHMRUpdate(useAuth, import.meta.hot))
|
||||
}
|
||||
```
|
||||
|
||||
## Setup Store Example
|
||||
|
||||
```ts
|
||||
import { defineStore, acceptHMRUpdate } from 'pinia'
|
||||
|
||||
export const useCounterStore = defineStore('counter', () => {
|
||||
const count = ref(0)
|
||||
const increment = () => count.value++
|
||||
return { count, increment }
|
||||
})
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot))
|
||||
}
|
||||
```
|
||||
|
||||
## Bundler Support
|
||||
|
||||
- **Vite:** Officially supported via `import.meta.hot`
|
||||
- **Webpack:** Uses `import.meta.webpackHot`
|
||||
- Any bundler implementing the `import.meta.hot` spec should work
|
||||
|
||||
## Nuxt
|
||||
|
||||
With `@pinia/nuxt`, `acceptHMRUpdate` is auto-imported but you still need to add the HMR snippet manually.
|
||||
|
||||
## Benefits
|
||||
|
||||
- Edit store logic without losing state
|
||||
- Add/remove state, actions, and getters on the fly
|
||||
- Faster development iteration
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/cookbook/hot-module-replacement.html
|
||||
-->
|
||||
119
.claude/skills/pinia/references/advanced-nuxt.md
Normal file
119
.claude/skills/pinia/references/advanced-nuxt.md
Normal file
@@ -0,0 +1,119 @@
|
||||
---
|
||||
name: nuxt-integration
|
||||
description: Using Pinia with Nuxt - auto-imports, SSR, and best practices
|
||||
---
|
||||
|
||||
# Nuxt Integration
|
||||
|
||||
Pinia works seamlessly with Nuxt 3/4, handling SSR, serialization, and XSS protection automatically.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npx nuxi@latest module add pinia
|
||||
```
|
||||
|
||||
This installs both `@pinia/nuxt` and `pinia`. If `pinia` isn't installed, add it manually.
|
||||
|
||||
> **npm users:** If you get `ERESOLVE unable to resolve dependency tree`, add to `package.json`:
|
||||
> ```json
|
||||
> "overrides": { "vue": "latest" }
|
||||
> ```
|
||||
|
||||
## Configuration
|
||||
|
||||
```ts
|
||||
// nuxt.config.ts
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@pinia/nuxt'],
|
||||
})
|
||||
```
|
||||
|
||||
## Auto Imports
|
||||
|
||||
These are automatically available:
|
||||
- `usePinia()` - get pinia instance
|
||||
- `defineStore()` - define stores
|
||||
- `storeToRefs()` - extract reactive refs
|
||||
- `acceptHMRUpdate()` - HMR support
|
||||
|
||||
**All stores in `app/stores/` (Nuxt 4) or `stores/` are auto-imported.**
|
||||
|
||||
### Custom Store Directories
|
||||
|
||||
```ts
|
||||
// nuxt.config.ts
|
||||
export default defineNuxtConfig({
|
||||
modules: ['@pinia/nuxt'],
|
||||
pinia: {
|
||||
storesDirs: ['./stores/**', './custom-folder/stores/**'],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Fetching Data in Pages
|
||||
|
||||
Use `callOnce()` for SSR-friendly data fetching:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const store = useStore()
|
||||
|
||||
// Run once, data persists across navigations
|
||||
await callOnce('user', () => store.fetchUser())
|
||||
</script>
|
||||
```
|
||||
|
||||
### Refetch on Navigation
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const store = useStore()
|
||||
|
||||
// Refetch on every navigation (like useFetch)
|
||||
await callOnce('user', () => store.fetchUser(), { mode: 'navigation' })
|
||||
</script>
|
||||
```
|
||||
|
||||
## Using Stores Outside Components
|
||||
|
||||
In navigation guards, middlewares, or other stores, pass the `pinia` instance:
|
||||
|
||||
```ts
|
||||
// middleware/auth.ts
|
||||
export default defineNuxtRouteMiddleware((to) => {
|
||||
const nuxtApp = useNuxtApp()
|
||||
const store = useStore(nuxtApp.$pinia)
|
||||
|
||||
if (to.meta.requiresAuth && !store.isLoggedIn) {
|
||||
return navigateTo('/login')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Most of the time, you don't need this - just use stores in components or other injection-aware contexts.
|
||||
|
||||
## Pinia Plugins with Nuxt
|
||||
|
||||
Create a Nuxt plugin:
|
||||
|
||||
```ts
|
||||
// plugins/myPiniaPlugin.ts
|
||||
import { PiniaPluginContext } from 'pinia'
|
||||
|
||||
function MyPiniaPlugin({ store }: PiniaPluginContext) {
|
||||
store.$subscribe((mutation) => {
|
||||
console.log(`[🍍 ${mutation.storeId}]: ${mutation.type}`)
|
||||
})
|
||||
return { creationTime: new Date() }
|
||||
}
|
||||
|
||||
export default defineNuxtPlugin(({ $pinia }) => {
|
||||
$pinia.use(MyPiniaPlugin)
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/ssr/nuxt.html
|
||||
-->
|
||||
121
.claude/skills/pinia/references/advanced-ssr.md
Normal file
121
.claude/skills/pinia/references/advanced-ssr.md
Normal file
@@ -0,0 +1,121 @@
|
||||
---
|
||||
name: server-side-rendering
|
||||
description: SSR setup, state hydration, and avoiding cross-request state pollution
|
||||
---
|
||||
|
||||
# Server Side Rendering (SSR)
|
||||
|
||||
Pinia works with SSR when stores are called at the top of `setup`, getters, or actions.
|
||||
|
||||
> **Using Nuxt?** See the [Nuxt integration](advanced-nuxt.md) instead.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// ✅ Works - pinia knows the app context in setup
|
||||
const main = useMainStore()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Using Store Outside setup()
|
||||
|
||||
Pass the `pinia` instance explicitly:
|
||||
|
||||
```ts
|
||||
const pinia = createPinia()
|
||||
const app = createApp(App)
|
||||
app.use(router)
|
||||
app.use(pinia)
|
||||
|
||||
router.beforeEach((to) => {
|
||||
// ✅ Pass pinia for correct SSR context
|
||||
const main = useMainStore(pinia)
|
||||
|
||||
if (to.meta.requiresAuth && !main.isLoggedIn) {
|
||||
return '/login'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## serverPrefetch()
|
||||
|
||||
Access pinia via `this.$pinia`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
serverPrefetch() {
|
||||
const store = useStore(this.$pinia)
|
||||
return store.fetchData()
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## onServerPrefetch()
|
||||
|
||||
Works normally:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const store = useStore()
|
||||
|
||||
onServerPrefetch(async () => {
|
||||
await store.fetchData()
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## State Hydration
|
||||
|
||||
Serialize state on server and hydrate on client.
|
||||
|
||||
### Server Side
|
||||
|
||||
Use [devalue](https://github.com/Rich-Harris/devalue) for XSS-safe serialization:
|
||||
|
||||
```ts
|
||||
import devalue from 'devalue'
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
const pinia = createPinia()
|
||||
const app = createApp(App)
|
||||
app.use(router)
|
||||
app.use(pinia)
|
||||
|
||||
// After rendering, state is available
|
||||
const serializedState = devalue(pinia.state.value)
|
||||
// Inject into HTML as global variable
|
||||
```
|
||||
|
||||
### Client Side
|
||||
|
||||
Hydrate before any `useStore()` call:
|
||||
|
||||
```ts
|
||||
const pinia = createPinia()
|
||||
const app = createApp(App)
|
||||
app.use(pinia)
|
||||
|
||||
// Hydrate from serialized state (e.g., from window.__pinia)
|
||||
if (typeof window !== 'undefined') {
|
||||
pinia.state.value = JSON.parse(window.__pinia)
|
||||
}
|
||||
```
|
||||
|
||||
## SSR Examples
|
||||
|
||||
- [Vitesse template](https://github.com/antfu/vitesse/blob/main/src/modules/pinia.ts)
|
||||
- [vite-plugin-ssr](https://vite-plugin-ssr.com/pinia)
|
||||
|
||||
## Key Points
|
||||
|
||||
1. Call stores inside functions, not at module scope
|
||||
2. Pass `pinia` instance when using stores outside components in SSR
|
||||
3. Hydrate state before calling any `useStore()`
|
||||
4. Use `devalue` or similar for safe serialization
|
||||
5. Avoid cross-request state pollution by creating fresh pinia per request
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/ssr/
|
||||
-->
|
||||
@@ -0,0 +1,115 @@
|
||||
---
|
||||
name: using-stores-outside-components
|
||||
description: Correctly using stores in navigation guards, plugins, and other non-component contexts
|
||||
---
|
||||
|
||||
# Using Stores Outside Components
|
||||
|
||||
Stores need the `pinia` instance, which is automatically injected in components. Outside components, you may need to provide it manually.
|
||||
|
||||
## Single Page Applications
|
||||
|
||||
Call stores **after** pinia is installed:
|
||||
|
||||
```ts
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { createPinia } from 'pinia'
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
// ❌ Fails - pinia not created yet
|
||||
const userStore = useUserStore()
|
||||
|
||||
const pinia = createPinia()
|
||||
const app = createApp(App)
|
||||
app.use(pinia)
|
||||
|
||||
// ✅ Works - pinia is active
|
||||
const userStore = useUserStore()
|
||||
```
|
||||
|
||||
## Navigation Guards
|
||||
|
||||
**Wrong:** Call at module level
|
||||
|
||||
```ts
|
||||
import { createRouter } from 'vue-router'
|
||||
const router = createRouter({ /* ... */ })
|
||||
|
||||
// ❌ May fail depending on import order
|
||||
const store = useUserStore()
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (store.isLoggedIn) { /* ... */ }
|
||||
})
|
||||
```
|
||||
|
||||
**Correct:** Call inside the guard
|
||||
|
||||
```ts
|
||||
router.beforeEach((to) => {
|
||||
// ✅ Called after pinia is installed
|
||||
const store = useUserStore()
|
||||
|
||||
if (to.meta.requiresAuth && !store.isLoggedIn) {
|
||||
return '/login'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## SSR Applications
|
||||
|
||||
Always pass the `pinia` instance to `useStore()`:
|
||||
|
||||
```ts
|
||||
const pinia = createPinia()
|
||||
const app = createApp(App)
|
||||
app.use(router)
|
||||
app.use(pinia)
|
||||
|
||||
router.beforeEach((to) => {
|
||||
// ✅ Pass pinia instance
|
||||
const main = useMainStore(pinia)
|
||||
|
||||
if (to.meta.requiresAuth && !main.isLoggedIn) {
|
||||
return '/login'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## serverPrefetch()
|
||||
|
||||
Access pinia via `this.$pinia`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
serverPrefetch() {
|
||||
const store = useStore(this.$pinia)
|
||||
return store.fetchData()
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## onServerPrefetch()
|
||||
|
||||
Works normally in `<script setup>`:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const store = useStore()
|
||||
|
||||
onServerPrefetch(async () => {
|
||||
// ✅ Just works
|
||||
await store.fetchData()
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Key Takeaway
|
||||
|
||||
Defer `useStore()` calls to functions that run after pinia is installed, rather than calling at module scope.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/core-concepts/outside-component-usage.html
|
||||
-->
|
||||
212
.claude/skills/pinia/references/best-practices-testing.md
Normal file
212
.claude/skills/pinia/references/best-practices-testing.md
Normal file
@@ -0,0 +1,212 @@
|
||||
---
|
||||
name: testing
|
||||
description: Unit testing stores and components with @pinia/testing
|
||||
---
|
||||
|
||||
# Testing Stores
|
||||
|
||||
## Unit Testing Stores
|
||||
|
||||
Create a fresh pinia instance for each test:
|
||||
|
||||
```ts
|
||||
import { setActivePinia, createPinia } from 'pinia'
|
||||
import { useCounterStore } from '../src/stores/counter'
|
||||
|
||||
describe('Counter Store', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
})
|
||||
|
||||
it('increments', () => {
|
||||
const counter = useCounterStore()
|
||||
expect(counter.n).toBe(0)
|
||||
counter.increment()
|
||||
expect(counter.n).toBe(1)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### With Plugins
|
||||
|
||||
```ts
|
||||
import { setActivePinia, createPinia } from 'pinia'
|
||||
import { createApp } from 'vue'
|
||||
import { somePlugin } from '../src/stores/plugin'
|
||||
|
||||
const app = createApp({})
|
||||
|
||||
beforeEach(() => {
|
||||
const pinia = createPinia().use(somePlugin)
|
||||
app.use(pinia)
|
||||
setActivePinia(pinia)
|
||||
})
|
||||
```
|
||||
|
||||
## Testing Components
|
||||
|
||||
Install `@pinia/testing`:
|
||||
|
||||
```bash
|
||||
npm i -D @pinia/testing
|
||||
```
|
||||
|
||||
Use `createTestingPinia()`:
|
||||
|
||||
```ts
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createTestingPinia } from '@pinia/testing'
|
||||
import { useSomeStore } from '@/stores/myStore'
|
||||
|
||||
const wrapper = mount(Counter, {
|
||||
global: {
|
||||
plugins: [createTestingPinia()],
|
||||
},
|
||||
})
|
||||
|
||||
const store = useSomeStore()
|
||||
|
||||
// Manipulate state directly
|
||||
store.name = 'new name'
|
||||
store.$patch({ name: 'new name' })
|
||||
|
||||
// Actions are stubbed by default
|
||||
store.someAction()
|
||||
expect(store.someAction).toHaveBeenCalledTimes(1)
|
||||
```
|
||||
|
||||
## Initial State
|
||||
|
||||
Set initial state for tests:
|
||||
|
||||
```ts
|
||||
const wrapper = mount(Counter, {
|
||||
global: {
|
||||
plugins: [
|
||||
createTestingPinia({
|
||||
initialState: {
|
||||
counter: { n: 20 }, // Store name → initial state
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Action Stubbing
|
||||
|
||||
### Execute Real Actions
|
||||
|
||||
```ts
|
||||
createTestingPinia({ stubActions: false })
|
||||
```
|
||||
|
||||
### Selective Stubbing
|
||||
|
||||
```ts
|
||||
// Only stub specific actions
|
||||
createTestingPinia({
|
||||
stubActions: ['increment', 'reset'],
|
||||
})
|
||||
|
||||
// Or use a function
|
||||
createTestingPinia({
|
||||
stubActions: (actionName, store) => {
|
||||
if (actionName.startsWith('set')) return true
|
||||
return false
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Mock Action Return Values
|
||||
|
||||
```ts
|
||||
import type { Mock } from 'vitest'
|
||||
|
||||
// After getting store
|
||||
store.someAction.mockResolvedValue('mocked value')
|
||||
```
|
||||
|
||||
## Mocking Getters
|
||||
|
||||
Getters are writable in tests:
|
||||
|
||||
```ts
|
||||
const pinia = createTestingPinia()
|
||||
const counter = useCounterStore(pinia)
|
||||
|
||||
counter.double = 3 // Override computed value
|
||||
|
||||
// Reset to default behavior
|
||||
counter.double = undefined
|
||||
counter.double // Now computed normally
|
||||
```
|
||||
|
||||
## Custom Spy Function
|
||||
|
||||
If not using Jest/Vitest with globals:
|
||||
|
||||
```ts
|
||||
import { vi } from 'vitest'
|
||||
|
||||
createTestingPinia({
|
||||
createSpy: vi.fn,
|
||||
})
|
||||
```
|
||||
|
||||
With Sinon:
|
||||
|
||||
```ts
|
||||
import sinon from 'sinon'
|
||||
|
||||
createTestingPinia({
|
||||
createSpy: sinon.spy,
|
||||
})
|
||||
```
|
||||
|
||||
## Pinia Plugins in Tests
|
||||
|
||||
Pass plugins to `createTestingPinia()`:
|
||||
|
||||
```ts
|
||||
import { somePlugin } from '../src/stores/plugin'
|
||||
|
||||
createTestingPinia({
|
||||
stubActions: false,
|
||||
plugins: [somePlugin],
|
||||
})
|
||||
```
|
||||
|
||||
**Don't use** `testingPinia.use(MyPlugin)` - pass plugins in options.
|
||||
|
||||
## Type-Safe Mocked Store
|
||||
|
||||
```ts
|
||||
import type { Mock } from 'vitest'
|
||||
import type { Store, StoreDefinition } from 'pinia'
|
||||
|
||||
function mockedStore<TStoreDef extends () => unknown>(
|
||||
useStore: TStoreDef
|
||||
): TStoreDef extends StoreDefinition<infer Id, infer State, infer Getters, infer Actions>
|
||||
? Store<Id, State, Record<string, never>, {
|
||||
[K in keyof Actions]: Actions[K] extends (...args: any[]) => any
|
||||
? Mock<Actions[K]>
|
||||
: Actions[K]
|
||||
}>
|
||||
: ReturnType<TStoreDef> {
|
||||
return useStore() as any
|
||||
}
|
||||
|
||||
// Usage
|
||||
const store = mockedStore(useSomeStore)
|
||||
store.someAction.mockResolvedValue('value') // Typed!
|
||||
```
|
||||
|
||||
## E2E Tests
|
||||
|
||||
No special handling needed - Pinia works normally.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/cookbook/testing.html
|
||||
-->
|
||||
389
.claude/skills/pinia/references/core-stores.md
Normal file
389
.claude/skills/pinia/references/core-stores.md
Normal file
@@ -0,0 +1,389 @@
|
||||
---
|
||||
name: stores
|
||||
description: Defining stores, state, getters, and actions in Pinia
|
||||
---
|
||||
|
||||
# Pinia Stores
|
||||
|
||||
Stores are defined using `defineStore()` with a unique name. Each store has three core concepts: **state**, **getters**, and **actions**.
|
||||
|
||||
## Defining Stores
|
||||
|
||||
### Option Stores
|
||||
|
||||
Similar to Vue's Options API:
|
||||
|
||||
```ts
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useCounterStore = defineStore('counter', {
|
||||
state: () => ({
|
||||
count: 0,
|
||||
name: 'Eduardo',
|
||||
}),
|
||||
getters: {
|
||||
doubleCount: (state) => state.count * 2,
|
||||
},
|
||||
actions: {
|
||||
increment() {
|
||||
this.count++
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Think of `state` as `data`, `getters` as `computed`, and `actions` as `methods`.
|
||||
|
||||
### Setup Stores (Recommended)
|
||||
|
||||
Uses Composition API syntax - more flexible and powerful:
|
||||
|
||||
```ts
|
||||
import { ref, computed } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useCounterStore = defineStore('counter', () => {
|
||||
const count = ref(0)
|
||||
const name = ref('Eduardo')
|
||||
const doubleCount = computed(() => count.value * 2)
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
return { count, name, doubleCount, increment }
|
||||
})
|
||||
```
|
||||
|
||||
In Setup Stores: `ref()` → state, `computed()` → getters, `function()` → actions.
|
||||
|
||||
**Important:** You must return all state properties for Pinia to track them.
|
||||
|
||||
### Using Stores
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { useCounterStore } from '@/stores/counter'
|
||||
|
||||
const store = useCounterStore()
|
||||
// Access: store.count, store.doubleCount, store.increment()
|
||||
</script>
|
||||
```
|
||||
|
||||
### Destructuring with storeToRefs
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useCounterStore } from '@/stores/counter'
|
||||
|
||||
const store = useCounterStore()
|
||||
|
||||
// ❌ Breaks reactivity
|
||||
const { name, doubleCount } = store
|
||||
|
||||
// ✅ Preserves reactivity for state/getters
|
||||
const { name, doubleCount } = storeToRefs(store)
|
||||
|
||||
// ✅ Actions can be destructured directly
|
||||
const { increment } = store
|
||||
</script>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## State
|
||||
|
||||
State is defined as a function returning the initial state.
|
||||
|
||||
### TypeScript
|
||||
|
||||
Type inference works automatically. For complex types:
|
||||
|
||||
```ts
|
||||
interface UserInfo {
|
||||
name: string
|
||||
age: number
|
||||
}
|
||||
|
||||
export const useUserStore = defineStore('user', {
|
||||
state: () => ({
|
||||
userList: [] as UserInfo[],
|
||||
user: null as UserInfo | null,
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
Or use an interface for the return type:
|
||||
|
||||
```ts
|
||||
interface State {
|
||||
userList: UserInfo[]
|
||||
user: UserInfo | null
|
||||
}
|
||||
|
||||
export const useUserStore = defineStore('user', {
|
||||
state: (): State => ({
|
||||
userList: [],
|
||||
user: null,
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
### Accessing and Modifying
|
||||
|
||||
```ts
|
||||
const store = useStore()
|
||||
store.count++
|
||||
```
|
||||
|
||||
```vue
|
||||
<input v-model="store.count" type="number" />
|
||||
```
|
||||
|
||||
### Mutating with $patch
|
||||
|
||||
Apply multiple changes at once:
|
||||
|
||||
```ts
|
||||
// Object syntax
|
||||
store.$patch({
|
||||
count: store.count + 1,
|
||||
name: 'DIO',
|
||||
})
|
||||
|
||||
// Function syntax (for complex mutations)
|
||||
store.$patch((state) => {
|
||||
state.items.push({ name: 'shoes', quantity: 1 })
|
||||
state.hasChanged = true
|
||||
})
|
||||
```
|
||||
|
||||
### Resetting State
|
||||
|
||||
Option Stores have built-in `$reset()`. For Setup Stores, implement your own:
|
||||
|
||||
```ts
|
||||
export const useCounterStore = defineStore('counter', () => {
|
||||
const count = ref(0)
|
||||
|
||||
function $reset() {
|
||||
count.value = 0
|
||||
}
|
||||
|
||||
return { count, $reset }
|
||||
})
|
||||
```
|
||||
|
||||
### Subscribing to State Changes
|
||||
|
||||
```ts
|
||||
cartStore.$subscribe((mutation, state) => {
|
||||
mutation.type // 'direct' | 'patch object' | 'patch function'
|
||||
mutation.storeId // 'cart'
|
||||
mutation.payload // patch object (only for 'patch object')
|
||||
|
||||
localStorage.setItem('cart', JSON.stringify(state))
|
||||
})
|
||||
|
||||
// Options
|
||||
cartStore.$subscribe(callback, { flush: 'sync' }) // Immediate
|
||||
cartStore.$subscribe(callback, { detached: true }) // Keep after unmount
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Getters
|
||||
|
||||
Getters are computed values, equivalent to Vue's `computed()`.
|
||||
|
||||
### Basic Getters
|
||||
|
||||
```ts
|
||||
getters: {
|
||||
doubleCount: (state) => state.count * 2,
|
||||
}
|
||||
```
|
||||
|
||||
### Accessing Other Getters
|
||||
|
||||
Use `this` with explicit return type:
|
||||
|
||||
```ts
|
||||
getters: {
|
||||
doubleCount: (state) => state.count * 2,
|
||||
doublePlusOne(): number {
|
||||
return this.doubleCount + 1
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
### Getters with Arguments
|
||||
|
||||
Return a function (note: loses caching):
|
||||
|
||||
```ts
|
||||
getters: {
|
||||
getUserById: (state) => {
|
||||
return (userId: string) => state.users.find((user) => user.id === userId)
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
Cache within parameterized getters:
|
||||
|
||||
```ts
|
||||
getters: {
|
||||
getActiveUserById(state) {
|
||||
const activeUsers = state.users.filter((user) => user.active)
|
||||
return (userId: string) => activeUsers.find((user) => user.id === userId)
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
### Accessing Other Stores in Getters
|
||||
|
||||
```ts
|
||||
import { useOtherStore } from './other-store'
|
||||
|
||||
getters: {
|
||||
combined(state) {
|
||||
const otherStore = useOtherStore()
|
||||
return state.localData + otherStore.data
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Actions
|
||||
|
||||
Actions are methods for business logic. Unlike getters, they can be asynchronous.
|
||||
|
||||
### Defining Actions
|
||||
|
||||
```ts
|
||||
actions: {
|
||||
increment() {
|
||||
this.count++
|
||||
},
|
||||
randomizeCounter() {
|
||||
this.count = Math.round(100 * Math.random())
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
### Async Actions
|
||||
|
||||
```ts
|
||||
actions: {
|
||||
async registerUser(login: string, password: string) {
|
||||
try {
|
||||
this.userData = await api.post({ login, password })
|
||||
} catch (error) {
|
||||
return error
|
||||
}
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
### Accessing Other Stores in Actions
|
||||
|
||||
```ts
|
||||
import { useAuthStore } from './auth-store'
|
||||
|
||||
actions: {
|
||||
async fetchUserPreferences() {
|
||||
const auth = useAuthStore()
|
||||
if (auth.isAuthenticated) {
|
||||
this.preferences = await fetchPreferences()
|
||||
}
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
**SSR:** Call all `useStore()` before any `await`:
|
||||
|
||||
```ts
|
||||
async orderCart() {
|
||||
// ✅ Call stores before await
|
||||
const user = useUserStore()
|
||||
|
||||
await apiOrderCart(user.token, this.items)
|
||||
// ❌ Don't call useStore() after await in SSR
|
||||
}
|
||||
```
|
||||
|
||||
### Subscribing to Actions
|
||||
|
||||
```ts
|
||||
const unsubscribe = someStore.$onAction(
|
||||
({ name, store, args, after, onError }) => {
|
||||
const startTime = Date.now()
|
||||
console.log(`Start "${name}" with params [${args.join(', ')}]`)
|
||||
|
||||
after((result) => {
|
||||
console.log(`Finished "${name}" after ${Date.now() - startTime}ms`)
|
||||
})
|
||||
|
||||
onError((error) => {
|
||||
console.warn(`Failed "${name}": ${error}`)
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
unsubscribe() // Cleanup
|
||||
```
|
||||
|
||||
Keep subscription after component unmount:
|
||||
|
||||
```ts
|
||||
someStore.$onAction(callback, true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Options API Helpers
|
||||
|
||||
```ts
|
||||
import { mapState, mapWritableState, mapActions } from 'pinia'
|
||||
import { useCounterStore } from '../stores/counter'
|
||||
|
||||
export default {
|
||||
computed: {
|
||||
// Readonly state/getters
|
||||
...mapState(useCounterStore, ['count', 'doubleCount']),
|
||||
// Writable state
|
||||
...mapWritableState(useCounterStore, ['count']),
|
||||
},
|
||||
methods: {
|
||||
...mapActions(useCounterStore, ['increment']),
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Accessing Global Providers in Setup Stores
|
||||
|
||||
```ts
|
||||
import { inject } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useSearchFilters = defineStore('search-filters', () => {
|
||||
const route = useRoute()
|
||||
const appProvided = inject('appProvided')
|
||||
|
||||
// Don't return these - access them directly in components
|
||||
return { /* ... */ }
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/core-concepts/
|
||||
- https://pinia.vuejs.org/core-concepts/state.html
|
||||
- https://pinia.vuejs.org/core-concepts/getters.html
|
||||
- https://pinia.vuejs.org/core-concepts/actions.html
|
||||
-->
|
||||
114
.claude/skills/pinia/references/features-composables.md
Normal file
114
.claude/skills/pinia/references/features-composables.md
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: composables-in-stores
|
||||
description: Using Vue composables within Pinia stores
|
||||
---
|
||||
|
||||
# Composables in Stores
|
||||
|
||||
Pinia stores can leverage Vue composables for reusable stateful logic.
|
||||
|
||||
## Option Stores
|
||||
|
||||
Call composables inside the `state` property, but only those returning writable refs:
|
||||
|
||||
```ts
|
||||
import { defineStore } from 'pinia'
|
||||
import { useLocalStorage } from '@vueuse/core'
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
user: useLocalStorage('pinia/auth/login', 'bob'),
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
**Works:** Composables returning `ref()`:
|
||||
- `useLocalStorage`
|
||||
- `useAsyncState`
|
||||
|
||||
**Doesn't work in Option Stores:**
|
||||
- Composables exposing functions
|
||||
- Composables exposing readonly data
|
||||
|
||||
## Setup Stores
|
||||
|
||||
More flexible - can use almost any composable:
|
||||
|
||||
```ts
|
||||
import { defineStore } from 'pinia'
|
||||
import { useMediaControls } from '@vueuse/core'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const useVideoPlayer = defineStore('video', () => {
|
||||
const videoElement = ref<HTMLVideoElement>()
|
||||
const src = ref('/data/video.mp4')
|
||||
const { playing, volume, currentTime, togglePictureInPicture } =
|
||||
useMediaControls(videoElement, { src })
|
||||
|
||||
function loadVideo(element: HTMLVideoElement, newSrc: string) {
|
||||
videoElement.value = element
|
||||
src.value = newSrc
|
||||
}
|
||||
|
||||
return {
|
||||
src,
|
||||
playing,
|
||||
volume,
|
||||
currentTime,
|
||||
loadVideo,
|
||||
togglePictureInPicture,
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** Don't return non-serializable DOM refs like `videoElement` - they're internal implementation details.
|
||||
|
||||
## SSR Considerations
|
||||
|
||||
### Option Stores with hydrate()
|
||||
|
||||
Define a `hydrate()` function to handle client-side hydration:
|
||||
|
||||
```ts
|
||||
import { defineStore } from 'pinia'
|
||||
import { useLocalStorage } from '@vueuse/core'
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
user: useLocalStorage('pinia/auth/login', 'bob'),
|
||||
}),
|
||||
|
||||
hydrate(state, initialState) {
|
||||
// Ignore server state, read from browser
|
||||
state.user = useLocalStorage('pinia/auth/login', 'bob')
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Setup Stores with skipHydrate()
|
||||
|
||||
Mark state that shouldn't hydrate from server:
|
||||
|
||||
```ts
|
||||
import { defineStore, skipHydrate } from 'pinia'
|
||||
import { useEyeDropper, useLocalStorage } from '@vueuse/core'
|
||||
|
||||
export const useColorStore = defineStore('colors', () => {
|
||||
const { isSupported, open, sRGBHex } = useEyeDropper()
|
||||
const lastColor = useLocalStorage('lastColor', sRGBHex)
|
||||
|
||||
return {
|
||||
// Skip hydration for client-only state
|
||||
lastColor: skipHydrate(lastColor),
|
||||
open, // Function - no hydration needed
|
||||
isSupported, // Boolean - not reactive
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
`skipHydrate()` only applies to state properties (refs), not functions or non-reactive values.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/cookbook/composables.html
|
||||
-->
|
||||
134
.claude/skills/pinia/references/features-composing-stores.md
Normal file
134
.claude/skills/pinia/references/features-composing-stores.md
Normal file
@@ -0,0 +1,134 @@
|
||||
---
|
||||
name: composing-stores
|
||||
description: Store-to-store communication and avoiding circular dependencies
|
||||
---
|
||||
|
||||
# Composing Stores
|
||||
|
||||
Stores can use each other for shared state and logic.
|
||||
|
||||
## Rule: Avoid Circular Dependencies
|
||||
|
||||
Two stores cannot directly read each other's state during setup:
|
||||
|
||||
```ts
|
||||
// ❌ Infinite loop
|
||||
const useX = defineStore('x', () => {
|
||||
const y = useY()
|
||||
y.name // Don't read here!
|
||||
return { name: ref('X') }
|
||||
})
|
||||
|
||||
const useY = defineStore('y', () => {
|
||||
const x = useX()
|
||||
x.name // Don't read here!
|
||||
return { name: ref('Y') }
|
||||
})
|
||||
```
|
||||
|
||||
**Solution:** Read in getters, computed, or actions:
|
||||
|
||||
```ts
|
||||
const useX = defineStore('x', () => {
|
||||
const y = useY()
|
||||
|
||||
// ✅ Read in computed/actions
|
||||
function doSomething() {
|
||||
const yName = y.name
|
||||
}
|
||||
|
||||
return { name: ref('X'), doSomething }
|
||||
})
|
||||
```
|
||||
|
||||
## Setup Stores: Use Store at Top
|
||||
|
||||
```ts
|
||||
import { defineStore } from 'pinia'
|
||||
import { useUserStore } from './user'
|
||||
|
||||
export const useCartStore = defineStore('cart', () => {
|
||||
const user = useUserStore()
|
||||
const list = ref([])
|
||||
|
||||
const summary = computed(() => {
|
||||
return `Hi ${user.name}, you have ${list.value.length} items`
|
||||
})
|
||||
|
||||
function purchase() {
|
||||
return apiPurchase(user.id, list.value)
|
||||
}
|
||||
|
||||
return { list, summary, purchase }
|
||||
})
|
||||
```
|
||||
|
||||
## Shared Getters
|
||||
|
||||
Call `useStore()` inside a getter:
|
||||
|
||||
```ts
|
||||
import { useUserStore } from './user'
|
||||
|
||||
export const useCartStore = defineStore('cart', {
|
||||
getters: {
|
||||
summary(state) {
|
||||
const user = useUserStore()
|
||||
return `Hi ${user.name}, you have ${state.list.length} items`
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Shared Actions
|
||||
|
||||
Call `useStore()` inside an action:
|
||||
|
||||
```ts
|
||||
import { useUserStore } from './user'
|
||||
import { apiOrderCart } from './api'
|
||||
|
||||
export const useCartStore = defineStore('cart', {
|
||||
actions: {
|
||||
async orderCart() {
|
||||
const user = useUserStore()
|
||||
|
||||
try {
|
||||
await apiOrderCart(user.token, this.items)
|
||||
this.emptyCart()
|
||||
} catch (err) {
|
||||
displayError(err)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## SSR: Call Stores Before Await
|
||||
|
||||
In async actions, call all stores before any `await`:
|
||||
|
||||
```ts
|
||||
actions: {
|
||||
async orderCart() {
|
||||
// ✅ All useStore() calls before await
|
||||
const user = useUserStore()
|
||||
const analytics = useAnalyticsStore()
|
||||
|
||||
try {
|
||||
await apiOrderCart(user.token, this.items)
|
||||
// ❌ Don't call useStore() after await (SSR issue)
|
||||
// const otherStore = useOtherStore()
|
||||
} catch (err) {
|
||||
displayError(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
This ensures the correct Pinia instance is used during SSR.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/cookbook/composing-stores.html
|
||||
-->
|
||||
203
.claude/skills/pinia/references/features-plugins.md
Normal file
203
.claude/skills/pinia/references/features-plugins.md
Normal file
@@ -0,0 +1,203 @@
|
||||
---
|
||||
name: plugins
|
||||
description: Extend stores with custom properties, methods, and behavior
|
||||
---
|
||||
|
||||
# Plugins
|
||||
|
||||
Plugins extend all stores with custom properties, methods, or behavior.
|
||||
|
||||
## Basic Plugin
|
||||
|
||||
```ts
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
function SecretPiniaPlugin() {
|
||||
return { secret: 'the cake is a lie' }
|
||||
}
|
||||
|
||||
const pinia = createPinia()
|
||||
pinia.use(SecretPiniaPlugin)
|
||||
|
||||
// In any store
|
||||
const store = useStore()
|
||||
store.secret // 'the cake is a lie'
|
||||
```
|
||||
|
||||
## Plugin Context
|
||||
|
||||
Plugins receive a context object:
|
||||
|
||||
```ts
|
||||
import { PiniaPluginContext } from 'pinia'
|
||||
|
||||
export function myPiniaPlugin(context: PiniaPluginContext) {
|
||||
context.pinia // pinia instance
|
||||
context.app // Vue app instance
|
||||
context.store // store being augmented
|
||||
context.options // store definition options
|
||||
}
|
||||
```
|
||||
|
||||
## Adding Properties
|
||||
|
||||
Return an object to add properties (tracked in devtools):
|
||||
|
||||
```ts
|
||||
pinia.use(() => ({ hello: 'world' }))
|
||||
```
|
||||
|
||||
Or set directly on store:
|
||||
|
||||
```ts
|
||||
pinia.use(({ store }) => {
|
||||
store.hello = 'world'
|
||||
// For devtools visibility in dev mode
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
store._customProperties.add('hello')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Adding State
|
||||
|
||||
Add to both `store` and `store.$state` for SSR/devtools:
|
||||
|
||||
```ts
|
||||
import { toRef, ref } from 'vue'
|
||||
|
||||
pinia.use(({ store }) => {
|
||||
if (!store.$state.hasOwnProperty('hasError')) {
|
||||
const hasError = ref(false)
|
||||
store.$state.hasError = hasError
|
||||
}
|
||||
store.hasError = toRef(store.$state, 'hasError')
|
||||
})
|
||||
```
|
||||
|
||||
## Adding External Properties
|
||||
|
||||
Wrap non-reactive objects with `markRaw()`:
|
||||
|
||||
```ts
|
||||
import { markRaw } from 'vue'
|
||||
import { router } from './router'
|
||||
|
||||
pinia.use(({ store }) => {
|
||||
store.router = markRaw(router)
|
||||
})
|
||||
```
|
||||
|
||||
## Custom Store Options
|
||||
|
||||
Define custom options consumed by plugins:
|
||||
|
||||
```ts
|
||||
// Store definition
|
||||
defineStore('search', {
|
||||
actions: {
|
||||
searchContacts() { /* ... */ },
|
||||
},
|
||||
debounce: {
|
||||
searchContacts: 300,
|
||||
},
|
||||
})
|
||||
|
||||
// Plugin reads custom option
|
||||
import debounce from 'lodash/debounce'
|
||||
|
||||
pinia.use(({ options, store }) => {
|
||||
if (options.debounce) {
|
||||
return Object.keys(options.debounce).reduce((acc, action) => {
|
||||
acc[action] = debounce(store[action], options.debounce[action])
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
For Setup Stores, pass options as third argument:
|
||||
|
||||
```ts
|
||||
defineStore(
|
||||
'search',
|
||||
() => { /* ... */ },
|
||||
{
|
||||
debounce: { searchContacts: 300 },
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## TypeScript Augmentation
|
||||
|
||||
### Custom Properties
|
||||
|
||||
```ts
|
||||
import 'pinia'
|
||||
import type { Router } from 'vue-router'
|
||||
|
||||
declare module 'pinia' {
|
||||
export interface PiniaCustomProperties {
|
||||
router: Router
|
||||
hello: string
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Custom State
|
||||
|
||||
```ts
|
||||
declare module 'pinia' {
|
||||
export interface PiniaCustomStateProperties<S> {
|
||||
hasError: boolean
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Options
|
||||
|
||||
```ts
|
||||
declare module 'pinia' {
|
||||
export interface DefineStoreOptionsBase<S, Store> {
|
||||
debounce?: Partial<Record<keyof StoreActions<Store>, number>>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Subscribe in Plugins
|
||||
|
||||
```ts
|
||||
pinia.use(({ store }) => {
|
||||
store.$subscribe(() => {
|
||||
// React to state changes
|
||||
})
|
||||
store.$onAction(() => {
|
||||
// React to actions
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Nuxt Plugin
|
||||
|
||||
Create a Nuxt plugin to add Pinia plugins:
|
||||
|
||||
```ts
|
||||
// plugins/myPiniaPlugin.ts
|
||||
import { PiniaPluginContext } from 'pinia'
|
||||
|
||||
function MyPiniaPlugin({ store }: PiniaPluginContext) {
|
||||
store.$subscribe((mutation) => {
|
||||
console.log(`[🍍 ${mutation.storeId}]: ${mutation.type}`)
|
||||
})
|
||||
return { creationTime: new Date() }
|
||||
}
|
||||
|
||||
export default defineNuxtPlugin(({ $pinia }) => {
|
||||
$pinia.use(MyPiniaPlugin)
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://pinia.vuejs.org/core-concepts/plugins.html
|
||||
-->
|
||||
436
.claude/skills/project-structure/SKILL.md
Normal file
436
.claude/skills/project-structure/SKILL.md
Normal file
@@ -0,0 +1,436 @@
|
||||
# Project Structure Skill
|
||||
|
||||
本 skill 定义项目的分层架构和文件组织规范,用于指导 Agent 在创建新页面、组件时遵循统一的目录结构。
|
||||
|
||||
## 核心原则
|
||||
|
||||
1. **页面放在 `pages/`** - 每个页面一个目录,包含 `index.vue`
|
||||
2. **组件放在 `components/`** - 公共组件直接放目录下,页面专属组件按页面名分子目录
|
||||
3. **页面专属组件与页面同名** - 如 `home` 页面的组件放在 `components/home/`
|
||||
4. **使用 easycom 自动加载** - 无需手动 import,组件通过文件路径自动生成标签名
|
||||
|
||||
## 组件放置规则(重要)
|
||||
|
||||
### 公共组件(跨页面复用)
|
||||
当用户要求创建**公共组件**时,直接放在 `components/` 根目录下:
|
||||
|
||||
```
|
||||
components/
|
||||
├── backNav.vue # 通用返回导航栏
|
||||
├── tabBar.vue # 通用底部栏
|
||||
├── modal.vue # 通用弹窗
|
||||
└── ...
|
||||
```
|
||||
|
||||
标签名:`<back-nav />`、`<tab-bar />`、`<modal />`
|
||||
|
||||
### 页面专属组件(仅特定页面使用)
|
||||
当组件只在某个页面内使用时,放在 `components/{pageName}/` 子目录下:
|
||||
|
||||
```
|
||||
components/
|
||||
├── home/ # 首页专属组件
|
||||
│ ├── status.vue
|
||||
│ └── overview.vue
|
||||
├── message/ # 消息页专属组件
|
||||
│ └── list.vue
|
||||
└── bluetooth/ # 蓝牙页专属组件
|
||||
└── device.vue
|
||||
```
|
||||
|
||||
标签名:`<home-status />`、`<message-list />`、`<bluetooth-device />`
|
||||
|
||||
### 判断依据
|
||||
|
||||
| 需求描述 | 放置位置 | 示例 |
|
||||
|----------|----------|------|
|
||||
| "做一个通用的返回导航" | `components/backNav.vue` | `<back-nav />` |
|
||||
| "做一个通用的弹窗组件" | `components/modal.vue` | `<modal />` |
|
||||
| "首页的项目列表组件" | `components/home/projectList.vue` | `<home-projectList />` |
|
||||
| "消息页的消息列表" | `components/message/list.vue` | `<message-list />` |
|
||||
| "蓝牙页的设备卡片" | `components/bluetooth/device.vue` | `<bluetooth-device />` |
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
src/
|
||||
├── pages/ # 页面目录
|
||||
│ ├── home/ # 首页
|
||||
│ │ └── index.vue
|
||||
│ ├── report/ # 报告页
|
||||
│ │ └── index.vue
|
||||
│ ├── message/ # 消息页
|
||||
│ │ └── index.vue
|
||||
│ ├── bluetooth/ # 蓝牙页
|
||||
│ │ └── index.vue
|
||||
│ └── work/ # 工作页
|
||||
│ └── index.vue
|
||||
│
|
||||
├── components/ # 组件目录
|
||||
│ ├── backNav.vue # 公共组件:通用返回导航栏
|
||||
│ │
|
||||
│ ├── home/ # 首页专属组件
|
||||
│ │ ├── homeNav.vue # 首页导航栏
|
||||
│ │ ├── overview.vue # 今日作业概览
|
||||
│ │ ├── status.vue # 实时作业状态
|
||||
│ │ ├── projectList.vue # 项目列表容器
|
||||
│ │ ├── list.vue # 项目列表项
|
||||
│ │ ├── progress.vue # 项目作业进度
|
||||
│ │ ├── construction.vue # 当前施工段
|
||||
│ │ ├── warning.vue # 异常警告容器
|
||||
│ │ └── warning_list.vue # 异常警告项
|
||||
│ │
|
||||
│ ├── message/ # 消息页专属组件
|
||||
│ │ └── list.vue # 消息列表项
|
||||
│ │
|
||||
│ └── bluetooth/ # 蓝牙页专属组件
|
||||
│ └── device.vue # 蓝牙设备卡片
|
||||
│
|
||||
├── composables/ # 组合式函数
|
||||
├── store/ # Pinia 状态管理
|
||||
├── api/ # 接口请求
|
||||
├── utils/ # 工具函数
|
||||
├── static/ # 静态资源
|
||||
└── layouts/ # 布局组件
|
||||
```
|
||||
|
||||
## 命名规范
|
||||
|
||||
### 文件命名
|
||||
- **页面**: `index.vue`(固定)
|
||||
- **组件**: `camelCase.vue`(如 `projectList.vue`)
|
||||
- **组合式函数**: `useXxx.ts`(如 `useCount.ts`)
|
||||
|
||||
### 组件标签名(easycom 规则)
|
||||
- **公共组件**: `backNav.vue` → `<back-nav />`
|
||||
- **页面专属组件**: `home/status.vue` → `<home-status />`
|
||||
- **嵌套组件**: `home/list.vue` → `<home-list />`
|
||||
|
||||
### easycom 自动扫描规则
|
||||
```json
|
||||
{
|
||||
"easycom": {
|
||||
"autoscan": true,
|
||||
"custom": {
|
||||
"^wd-(.*)": "@wot-ui/ui/components/wd-$1/wd-$1.vue",
|
||||
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### easycom 自动生成标签名规则
|
||||
| 文件路径 | 自动生成标签名 |
|
||||
|----------|----------------|
|
||||
| `components/backNav.vue` | `<back-nav />` |
|
||||
| `components/modal.vue` | `<modal />` |
|
||||
| `components/home/status.vue` | `<home-status />` |
|
||||
| `components/message/list.vue` | `<message-list />` |
|
||||
| `components/bluetooth/device.vue` | `<bluetooth-device />` |
|
||||
|
||||
## 组件拆分原则
|
||||
|
||||
### 何时拆分组件
|
||||
1. **模板超过 100 行** - 拆分为子组件
|
||||
2. **重复使用的 UI 块** - 提取为独立组件
|
||||
3. **逻辑独立的功能块** - 拆分便于维护
|
||||
|
||||
### 拆分模式
|
||||
```
|
||||
页面容器组件(如 projectList.vue)
|
||||
└── 列表项组件(如 projectList_list.vue)
|
||||
|
||||
页面容器组件(如 warning.vue)
|
||||
└── 列表项组件(如 warning_list.vue)
|
||||
```
|
||||
|
||||
### 示例:项目列表
|
||||
```
|
||||
components/home/
|
||||
├── projectList.vue # 容器:卡片标题 + card-body
|
||||
└── projectList_list.vue # 内容:项目信息 + 参数 + 操作按钮
|
||||
```
|
||||
|
||||
使用方式:
|
||||
```vue
|
||||
<home-projectList>
|
||||
<home-projectList_list />
|
||||
</home-projectList>
|
||||
```
|
||||
|
||||
## 创建新页面步骤
|
||||
|
||||
1. **创建页面目录**
|
||||
```
|
||||
src/pages/{pageName}/index.vue
|
||||
```
|
||||
|
||||
2. **创建页面专属组件目录**(如需要)
|
||||
```
|
||||
src/components/{pageName}/
|
||||
```
|
||||
|
||||
3. **配置路由**(如需要)
|
||||
```json
|
||||
// src/pages.json
|
||||
{
|
||||
"path": "pages/{pageName}/index",
|
||||
"type": "page",
|
||||
"style": {
|
||||
"navigationBarTitleText": "页面标题"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
4. **使用组件**
|
||||
```vue
|
||||
<template>
|
||||
<view class="page">
|
||||
<!-- 示例:替换为具体组件名,如 <home-component /> -->
|
||||
<home-component />
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## 页面专属组件 vs 公共组件
|
||||
|
||||
| 类型 | 位置 | 标签名 | 示例 |
|
||||
|------|------|--------|------|
|
||||
| 公共组件 | `components/` 根目录 | `{name}` | `<back-nav />` |
|
||||
| 页面专属组件 | `components/{pageName}/` | `{pageName}-{name}` | `<home-status />` |
|
||||
|
||||
## 页面样式规范
|
||||
|
||||
### 内容区域样式
|
||||
所有使用自定义导航栏(`<back-nav />`)的页面,`.content` 容器必须使用以下样式:
|
||||
|
||||
```css
|
||||
.content {
|
||||
padding: 16px;
|
||||
padding-top: 72px;
|
||||
}
|
||||
```
|
||||
|
||||
- `padding-top: 72px` 为导航栏预留空间,避免内容被遮挡
|
||||
- `padding: 16px` 保持左右边距一致
|
||||
|
||||
### 卡片样式规范(重要)
|
||||
每个组件自身就是一个卡片,**页面不要用额外的 `.card` 容器包裹组件**,否则多个组件会合并成一个卡片。
|
||||
|
||||
**卡片间距规则**:
|
||||
- 卡片之间间距统一为 **12px**
|
||||
- 页面通过 `gap: 12px` 设置间距,**组件内部不要添加 margin**
|
||||
- 组件只负责自身样式(背景、圆角、内边距),不负责与其他组件的间距
|
||||
|
||||
**正确做法** - 页面用 gap 设置间距:
|
||||
```vue
|
||||
<!-- 页面 -->
|
||||
<template>
|
||||
<view class="page">
|
||||
<back-nav title="页面标题" />
|
||||
<view class="content">
|
||||
<component-a />
|
||||
<component-b />
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<template>
|
||||
<view class="card">
|
||||
<!-- 内容 -->
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<!-- 组件 a.vue -->
|
||||
<style scoped>
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px; /* 卡片间距 */
|
||||
}
|
||||
</style>
|
||||
|
||||
<style scoped>
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
/* 不要添加 margin */
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
**错误做法** - 组件添加 margin 影响间距:
|
||||
```css
|
||||
/* 错误:组件添加 margin */
|
||||
.card {
|
||||
margin-bottom: 16px; /* 不要用 margin */
|
||||
}
|
||||
```
|
||||
|
||||
**组件卡片统一样式:**
|
||||
```css
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
```
|
||||
|
||||
**例外情况** - 多个子组件需要合并展示时:
|
||||
当明确要求将多个组件放在同一个卡片内时,由最外层容器组件统一设置卡片样式,子组件背景透明:
|
||||
```css
|
||||
/* 容器组件 */
|
||||
.container {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
/* 子组件 */
|
||||
.child {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
```
|
||||
|
||||
### 页面模板示例
|
||||
```vue
|
||||
<template>
|
||||
<view class="page">
|
||||
<back-nav title="页面标题" />
|
||||
|
||||
<view class="content">
|
||||
<view class="card">
|
||||
<!-- 卡片内容 -->
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
background-color: #EAEFF9;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 16px;
|
||||
padding-top: 72px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### 字体规范
|
||||
项目使用三级字体体系:
|
||||
|
||||
| 级别 | 字号 | 用途 | 示例 |
|
||||
|------|------|------|------|
|
||||
| 一级 | 22px | 最大标题 | 页面标题、卡片大标题 |
|
||||
| 二级 | 18px | 次级正常字体 | 正文、列表项、表单标签 |
|
||||
| 三级 | 14px | 最小描述字体 | 辅助说明、placeholder、元信息 |
|
||||
|
||||
**CSS 变量:**
|
||||
```css
|
||||
/* 一级标题 */
|
||||
--font-size-title: 22px;
|
||||
|
||||
/* 二级正文 */
|
||||
--font-size-body: 18px;
|
||||
|
||||
/* 三级描述 */
|
||||
--font-size-caption: 14px;
|
||||
```
|
||||
|
||||
**使用示例:**
|
||||
```vue
|
||||
<template>
|
||||
<view class="card">
|
||||
<text class="title">
|
||||
项目名称
|
||||
</text>
|
||||
<text class="body">
|
||||
项目描述内容
|
||||
</text>
|
||||
<text class="caption">
|
||||
辅助说明文字
|
||||
</text>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.title {
|
||||
font-size: 22px;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.body {
|
||||
font-size: 18px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.caption {
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **不要在页面中直接写大段模板** - 超过 100 行考虑拆分
|
||||
2. **组件样式使用 scoped** - 避免样式污染
|
||||
3. **组件 props 要有默认值** - 提高组件易用性
|
||||
4. **事件命名使用 kebab-case** - 如 `@handle-click`
|
||||
5. **插槽优先于 props 传内容** - 灵活性更高
|
||||
6. **禁止使用 git 提交** - 代码的改动必须经过手动提交
|
||||
|
||||
## UI 组件库使用规范(重要)
|
||||
|
||||
项目使用两套 UI 组件库,按场景分工:
|
||||
|
||||
### uni-ui(表单/表格场景)
|
||||
**仅用于**表单、表格相关的组件:
|
||||
- 下拉选择:`<uni-data-select>`
|
||||
- 单选框:`<uni-radio>` / `<uni-radio-group>`
|
||||
- 多选框:`<uni-checkbox>` / `<uni-checkbox-group>`
|
||||
- 日期选择:`<uni-datetime-picker>`
|
||||
- 输入框:`<uni-easyinput>`
|
||||
- 数据选择器:`<uni-data-picker>`
|
||||
- 图标:`<uni-icons>`
|
||||
|
||||
官网:https://uniapp.dcloud.net.cn/component/uniui/uni-data-select.html
|
||||
|
||||
### wot-ui(其他所有场景)
|
||||
**除表单表格外**,其他所有 UI 组件统一使用 wot-ui:
|
||||
- 按钮:`<wd-button>`
|
||||
- 图标:`<wd-icon>`
|
||||
- 弹窗:`<wd-dialog>`
|
||||
- 导航栏:`<wd-nav-bar>`
|
||||
- 标签:`<wd-tag>`
|
||||
- 步骤条:`<wd-steps>`
|
||||
- 加载:`<wd-loading>`
|
||||
- 等等
|
||||
|
||||
### 快速判断
|
||||
|
||||
| 场景 | 使用库 | 组件示例 |
|
||||
|------|--------|----------|
|
||||
| 输入框 | uni-ui | `<uni-easyinput>` |
|
||||
| 下拉选择 | uni-ui | `<uni-data-select>` |
|
||||
| 单选/多选 | uni-ui | `<uni-radio>` / `<uni-checkbox>` |
|
||||
| 日期时间选择 | uni-ui | `<uni-datetime-picker>` |
|
||||
| 按钮 | wot-ui | `<wd-button>` |
|
||||
| 图标 | wot-ui | `<wd-icon>` |
|
||||
| 弹窗/通知 | wot-ui | `<wd-dialog>` / `<wd-toast>` |
|
||||
| 导航栏 | wot-ui | `<wd-nav-bar>` |
|
||||
| 标签/徽标 | wot-ui | `<wd-tag>` / `<wd-badge>` |
|
||||
| 表格展示 | uni-ui | `<uni-table>` |
|
||||
54
.claude/skills/uni-app/GENERATION.md
Normal file
54
.claude/skills/uni-app/GENERATION.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Generation Info
|
||||
|
||||
- **Source:** `sources/uniapp`
|
||||
- **Git SHA:** `91423a240a5b0714fc5e7e13bd3f93a79b8cc8d7`
|
||||
- **Generated:** 2026-01-30
|
||||
|
||||
## Generated Skills
|
||||
|
||||
| Category | File | Description |
|
||||
|----------|------|-------------|
|
||||
| Core | core-framework.md | Framework basics, platform support, condition compilation |
|
||||
| Core | core-view-components.md | Container components: view, scroll-view, swiper, movable-area |
|
||||
| Core | core-form-components.md | Form controls: input, textarea, picker, checkbox, radio |
|
||||
| Features | feature-media-components.md | Media: image, video, camera, map, live-player |
|
||||
| Features | feature-navigation.md | Navigation: navigator, routing APIs |
|
||||
| Features | feature-network.md | Network: request, upload, download, WebSocket |
|
||||
| Features | feature-storage.md | Storage: localStorage, file system |
|
||||
| Features | feature-system-info.md | System: device info, network, screen, vibration |
|
||||
| Features | feature-file-operations.md | Files: image/video selection, file operations |
|
||||
| Features | feature-location.md | Location: geolocation, map component |
|
||||
| Features | feature-ui-feedback.md | UI: toast, modal, loading, action sheet |
|
||||
| Features | feature-lifecycle.md | Lifecycle: app and page hooks |
|
||||
| Config | config-pages.md | pages.json configuration |
|
||||
| Config | config-manifest.md | manifest.json configuration |
|
||||
|
||||
## Source Documentation Structure
|
||||
|
||||
```
|
||||
sources/uniapp/docs/
|
||||
├── README.md # Framework overview
|
||||
├── api/ # API documentation
|
||||
│ ├── README.md # API overview
|
||||
│ ├── request/ # Network APIs
|
||||
│ ├── storage/ # Storage APIs
|
||||
│ ├── media/ # Media APIs
|
||||
│ ├── file/ # File APIs
|
||||
│ ├── location/ # Location APIs
|
||||
│ ├── ui/ # UI APIs
|
||||
│ └── system/ # System APIs
|
||||
├── component/ # Component documentation
|
||||
├── collocation/ # Configuration
|
||||
│ ├── pages.md # pages.json
|
||||
│ ├── manifest.md # manifest.json
|
||||
│ └── manifest-app.md # App-specific manifest
|
||||
├── tutorial/ # Tutorials
|
||||
└── quickstart.md # Getting started
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Skills focus on practical usage patterns and code examples
|
||||
- Platform-specific differences are highlighted where relevant
|
||||
- Configuration files include common use cases for each platform
|
||||
- API skills include both callback and Promise usage patterns
|
||||
113
.claude/skills/uni-app/SKILL.md
Normal file
113
.claude/skills/uni-app/SKILL.md
Normal file
@@ -0,0 +1,113 @@
|
||||
---
|
||||
name: uni-app
|
||||
description: Comprehensive skill reference for uni-app cross-platform development framework
|
||||
metadata:
|
||||
author: FlippeDround
|
||||
version: "2026.1.30"
|
||||
source: Generated from https://gitcode.com/dcloud/unidocs-zh, skills located at https://github.com/antfu/skills
|
||||
---
|
||||
|
||||
> The skill is based on uni-app documentation, generated at 2026-01-30.
|
||||
|
||||
uni-app is a Vue.js-based cross-platform framework for developing applications that run on iOS, Android, HarmonyOS, Web (responsive), and various mini-program platforms (WeChat/Alipay/Baidu/Douyin/Feishu/QQ/Kuaishou/DingTalk/Taobao/Jingdong/Xiaohongshu).
|
||||
|
||||
## Core
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Core Framework | Project structure, platform support, condition compilation | [core-framework](references/core-framework.md) |
|
||||
| View Components | view, scroll-view, swiper, movable-area, cover-view | [core-view-components](references/core-view-components.md) |
|
||||
| Form Components | input, textarea, picker, checkbox, radio, switch, slider | [core-form-components](references/core-form-components.md) |
|
||||
|
||||
## Features
|
||||
|
||||
### UI Components
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Media Components | image, video, camera, live-player, map | [feature-media-components](references/feature-media-components.md) |
|
||||
| Navigation | navigator, routing, page navigation | [feature-navigation](references/feature-navigation.md) |
|
||||
| UI Feedback | toast, modal, loading, action sheet, pull refresh | [feature-ui-feedback](references/feature-ui-feedback.md) |
|
||||
|
||||
### APIs
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Network | HTTP requests, file upload/download, WebSocket | [feature-network](references/feature-network.md) |
|
||||
| Storage | Local storage, file system, caching | [feature-storage](references/feature-storage.md) |
|
||||
| System Info | Device info, network status, screen, vibration | [feature-system-info](references/feature-system-info.md) |
|
||||
| File Operations | Image/video selection, file system operations | [feature-file-operations](references/feature-file-operations.md) |
|
||||
| Location | Geolocation, map component, address selection | [feature-location](references/feature-location.md) |
|
||||
| Lifecycle | App and page lifecycle hooks | [feature-lifecycle](references/feature-lifecycle.md) |
|
||||
|
||||
## Configuration
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| pages.json | Page routing, tab bar, global styles, sub-packages | [config-pages](references/config-pages.md) |
|
||||
| manifest.json | App config, permissions, platform settings | [config-manifest](references/config-manifest.md) |
|
||||
|
||||
## Platform Support
|
||||
|
||||
| Platform | Support Level |
|
||||
|----------|---------------|
|
||||
| iOS App | Full support |
|
||||
| Android App | Full support |
|
||||
| HarmonyOS Next | Full support |
|
||||
| H5/Web | Full support |
|
||||
| WeChat Mini Program | Full support |
|
||||
| Alipay Mini Program | Full support |
|
||||
| Baidu Smart Program | Full support |
|
||||
| Douyin Mini Program | Full support |
|
||||
| QQ Mini Program | Full support |
|
||||
| Kuaishou Mini Program | Full support |
|
||||
| Feishu Mini Program | Full support |
|
||||
| JD Mini Program | Full support |
|
||||
| HarmonyOS Meta Service | Full support |
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Condition Compilation
|
||||
|
||||
Use special comments to write platform-specific code:
|
||||
|
||||
```vue
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<view>App only</view>
|
||||
<!-- #endif -->
|
||||
|
||||
<!-- #ifdef MP-WEIXIN -->
|
||||
<view>WeChat only</view>
|
||||
<!-- #endif -->
|
||||
```
|
||||
|
||||
### API Promise Support
|
||||
|
||||
Most uni-app APIs support Promise when no callback is provided:
|
||||
|
||||
```javascript
|
||||
const res = await uni.request({ url: 'https://api.example.com' })
|
||||
```
|
||||
|
||||
### Cross-Platform Best Practices
|
||||
|
||||
1. Use uni-app components and APIs instead of platform-specific ones
|
||||
2. Use condition compilation for platform-specific features
|
||||
3. Test on all target platforms
|
||||
4. Use rpx for responsive layouts
|
||||
5. Handle platform differences in manifest.json
|
||||
6. must use uni-helper tools
|
||||
|
||||
|
||||
### MCP扩展
|
||||
|
||||
当需要查询 uni-app 官方文档时,优先调用 `search-docs-by-Uniapp-official` MCP 工具搜索相关 API 文档和使用示例。
|
||||
|
||||
**使用场景:**
|
||||
- 用户询问特定 API 的详细用法
|
||||
- 需要官方文档中的代码示例
|
||||
- 查询组件的属性和事件
|
||||
- 了解 API 的平台兼容性
|
||||
|
||||
**工具安装:**
|
||||
如果检测到该 MCP 工具不可用,引导用户访问 https://github.com/uni-helper/mcp 进行安装。
|
||||
370
.claude/skills/uni-app/references/config-manifest.md
Normal file
370
.claude/skills/uni-app/references/config-manifest.md
Normal file
@@ -0,0 +1,370 @@
|
||||
---
|
||||
name: Manifest.json Configuration
|
||||
description: App configuration, permissions, and platform-specific settings
|
||||
---
|
||||
|
||||
# Manifest.json Configuration
|
||||
|
||||
`manifest.json` is the application configuration file, defining app name, icon, permissions, and platform-specific settings.
|
||||
|
||||
## Basic Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "My App",
|
||||
"appid": "__UNI__XXXXXXX",
|
||||
"description": "App description",
|
||||
"versionName": "1.0.0",
|
||||
"versionCode": 100,
|
||||
"locale": "auto",
|
||||
"debug": false
|
||||
}
|
||||
```
|
||||
|
||||
### Basic Properties
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| name | String | App name |
|
||||
| appid | String | DCloud app ID |
|
||||
| description | String | App description |
|
||||
| versionName | String | Version name (1.0.0) |
|
||||
| versionCode | Number | Version code (integer) |
|
||||
| locale | String | Default language |
|
||||
| debug | Boolean | Debug mode |
|
||||
| networkTimeout | Object | Network timeout settings |
|
||||
| uniStatistics | Object | Statistics configuration |
|
||||
|
||||
## Network Timeout
|
||||
|
||||
```json
|
||||
{
|
||||
"networkTimeout": {
|
||||
"request": 60000,
|
||||
"connectSocket": 60000,
|
||||
"uploadFile": 60000,
|
||||
"downloadFile": 60000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## App Configuration (app-plus)
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"splashscreen": {
|
||||
"alwaysShowBeforeRender": true,
|
||||
"autoclose": true,
|
||||
"waiting": true
|
||||
},
|
||||
"screenOrientation": ["portrait-primary"],
|
||||
"modules": {
|
||||
"OAuth": {},
|
||||
"Payment": {},
|
||||
"Push": {}
|
||||
},
|
||||
"distribute": {
|
||||
"android": {
|
||||
"permissions": [
|
||||
"<uses-permission android:name=\"android.permission.INTERNET\" />"
|
||||
],
|
||||
"minSdkVersion": 21,
|
||||
"targetSdkVersion": 30
|
||||
},
|
||||
"ios": {
|
||||
"capabilities": {
|
||||
"entitlements": {
|
||||
"com.apple.developer.push": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"sdkConfigs": {
|
||||
"payment": {
|
||||
"alipay": {},
|
||||
"weixin": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"optimization": {
|
||||
"subPackages": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Splash Screen
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| alwaysShowBeforeRender | Boolean | Show until first page renders |
|
||||
| autoclose | Boolean | Auto close splash screen |
|
||||
| waiting | Boolean | Show loading indicator |
|
||||
|
||||
## Mini-Program Configuration
|
||||
|
||||
### WeChat (mp-weixin)
|
||||
|
||||
```json
|
||||
{
|
||||
"mp-weixin": {
|
||||
"appid": "wx1234567890",
|
||||
"setting": {
|
||||
"urlCheck": false,
|
||||
"es6": true,
|
||||
"postcss": true,
|
||||
"minified": true
|
||||
},
|
||||
"usingComponents": true,
|
||||
"permission": {
|
||||
"scope.userLocation": {
|
||||
"desc": "Your location is needed"
|
||||
}
|
||||
},
|
||||
"requiredPrivateInfos": [
|
||||
"getLocation"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Alipay (mp-alipay)
|
||||
|
||||
```json
|
||||
{
|
||||
"mp-alipay": {
|
||||
"appid": "2021...",
|
||||
"allowsAlignRight": true,
|
||||
"component2": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Baidu (mp-baidu)
|
||||
|
||||
```json
|
||||
{
|
||||
"mp-baidu": {
|
||||
"appid": "12345678",
|
||||
"navigationBarForceEnable": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Douyin (mp-toutiao)
|
||||
|
||||
```json
|
||||
{
|
||||
"mp-toutiao": {
|
||||
"appid": "tt...",
|
||||
"setting": {
|
||||
"es6": true,
|
||||
"minified": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## H5 Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"h5": {
|
||||
"title": "My App",
|
||||
"template": "index.html",
|
||||
"router": {
|
||||
"mode": "hash",
|
||||
"base": "./"
|
||||
},
|
||||
"optimization": {
|
||||
"treeShaking": {
|
||||
"enable": true
|
||||
}
|
||||
},
|
||||
"publicPath": "./",
|
||||
"devServer": {
|
||||
"port": 8080,
|
||||
"disableHostCheck": true
|
||||
},
|
||||
"sdkConfigs": {
|
||||
"maps": {
|
||||
"qqmap": {
|
||||
"key": "..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Vue Configuration
|
||||
|
||||
### Vue 2
|
||||
|
||||
```json
|
||||
{
|
||||
"vueVersion": "2",
|
||||
"sassImplementationName": "dart-sass"
|
||||
}
|
||||
```
|
||||
|
||||
### Vue 3
|
||||
|
||||
```json
|
||||
{
|
||||
"vueVersion": "3"
|
||||
}
|
||||
```
|
||||
|
||||
## Permission Configuration
|
||||
|
||||
### Android Permissions
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"distribute": {
|
||||
"android": {
|
||||
"permissions": [
|
||||
"<uses-permission android:name=\"android.permission.INTERNET\" />",
|
||||
"<uses-permission android:name=\"android.permission.CAMERA\" />",
|
||||
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />",
|
||||
"<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />",
|
||||
"<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### iOS Privacy Descriptions
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"distribute": {
|
||||
"ios": {
|
||||
"privacyDescription": {
|
||||
"NSCameraUsageDescription": "Camera access is needed for scanning QR codes",
|
||||
"NSPhotoLibraryUsageDescription": "Photo access is needed for uploading images",
|
||||
"NSLocationWhenInUseUsageDescription": "Location is needed for finding nearby stores"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Common Module Configuration
|
||||
|
||||
### OAuth (Login)
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"modules": {
|
||||
"OAuth": {}
|
||||
},
|
||||
"distribute": {
|
||||
"sdkConfigs": {
|
||||
"oauth": {
|
||||
"weixin": {
|
||||
"appid": "wx...",
|
||||
"appsecret": "...",
|
||||
"UniversalLinks": "https://..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Payment
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"modules": {
|
||||
"Payment": {}
|
||||
},
|
||||
"distribute": {
|
||||
"sdkConfigs": {
|
||||
"payment": {
|
||||
"alipay": {},
|
||||
"weixin": {
|
||||
"appid": "wx..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Push Notifications
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"modules": {
|
||||
"Push": {}
|
||||
},
|
||||
"distribute": {
|
||||
"sdkConfigs": {
|
||||
"push": {
|
||||
"unipush": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Share
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"modules": {
|
||||
"Share": {}
|
||||
},
|
||||
"distribute": {
|
||||
"sdkConfigs": {
|
||||
"share": {
|
||||
"weixin": {
|
||||
"appid": "wx..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Statistics Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"uniStatistics": {
|
||||
"enable": true
|
||||
},
|
||||
"app-plus": {
|
||||
"uniStatistics": {
|
||||
"enable": true
|
||||
}
|
||||
},
|
||||
"mp-weixin": {
|
||||
"uniStatistics": {
|
||||
"enable": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/collocation/manifest.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/collocation/manifest-app.md
|
||||
-->
|
||||
270
.claude/skills/uni-app/references/config-pages.md
Normal file
270
.claude/skills/uni-app/references/config-pages.md
Normal file
@@ -0,0 +1,270 @@
|
||||
---
|
||||
name: Pages.json Configuration
|
||||
description: Page routing, tab bar, and global style configuration
|
||||
---
|
||||
|
||||
# Pages.json Configuration
|
||||
|
||||
`pages.json` is the global configuration file for uni-app, defining page routes, window styles, native navigation bar, and tab bar.
|
||||
|
||||
## Basic Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [
|
||||
{
|
||||
"path": "pages/index/index",
|
||||
"style": {
|
||||
"navigationBarTitleText": "Home"
|
||||
}
|
||||
}
|
||||
],
|
||||
"globalStyle": {
|
||||
"navigationBarTextStyle": "black",
|
||||
"navigationBarBackgroundColor": "#F8F8F8"
|
||||
},
|
||||
"tabBar": {
|
||||
"list": [
|
||||
{ "pagePath": "pages/index/index", "text": "Home" }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Root Properties
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
|----------|------|----------|-------------|
|
||||
| pages | Array | Yes | Page routes |
|
||||
| globalStyle | Object | No | Default window style |
|
||||
| tabBar | Object | No | Tab bar configuration |
|
||||
| condition | Object | No | Launch mode (dev only) |
|
||||
| subPackages | Array | No | Sub-packages |
|
||||
| preloadRule | Object | No | Preload rules (MP) |
|
||||
| easycom | Object | No | Auto component import |
|
||||
| leftWindow/topWindow/rightWindow | Object | No | Multi-window (H5) |
|
||||
|
||||
## Pages Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [
|
||||
{
|
||||
"path": "pages/index/index",
|
||||
"style": {
|
||||
"navigationBarTitleText": "Home",
|
||||
"enablePullDownRefresh": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/detail/detail",
|
||||
"style": {
|
||||
"navigationBarTitleText": "Detail",
|
||||
"navigationStyle": "custom"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Page Style Options
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| navigationBarTitleText | String | Navigation title |
|
||||
| navigationBarTextStyle | String | Title color: black/white |
|
||||
| navigationBarBackgroundColor | HexColor | Nav background |
|
||||
| navigationStyle | String | default/custom |
|
||||
| enablePullDownRefresh | Boolean | Enable pull refresh |
|
||||
| backgroundColor | HexColor | Background color |
|
||||
| backgroundTextStyle | String | dark/light |
|
||||
| onReachBottomDistance | Number | Bottom distance (px) |
|
||||
| disableScroll | Boolean | Disable scroll (MP) |
|
||||
| usingComponents | Object | Using custom components |
|
||||
|
||||
## Global Style
|
||||
|
||||
Applied to all pages unless overridden.
|
||||
|
||||
```json
|
||||
{
|
||||
"globalStyle": {
|
||||
"navigationBarTextStyle": "black",
|
||||
"navigationBarTitleText": "My App",
|
||||
"navigationBarBackgroundColor": "#F8F8F8",
|
||||
"backgroundColor": "#F8F8F8",
|
||||
"backgroundTextStyle": "dark",
|
||||
"enablePullDownRefresh": false,
|
||||
"onReachBottomDistance": 50,
|
||||
"rpxCalcMaxDeviceWidth": 960,
|
||||
"rpxCalcBaseDeviceWidth": 375,
|
||||
"rpxCalcIncludeWidth": 750
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Tab Bar Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"tabBar": {
|
||||
"color": "#7A7E83",
|
||||
"selectedColor": "#3cc51f",
|
||||
"backgroundColor": "#ffffff",
|
||||
"borderStyle": "black",
|
||||
"list": [
|
||||
{
|
||||
"pagePath": "pages/index/index",
|
||||
"text": "Home",
|
||||
"iconPath": "static/image/home.png",
|
||||
"selectedIconPath": "static/image/home-active.png"
|
||||
},
|
||||
{
|
||||
"pagePath": "pages/category/category",
|
||||
"text": "Category",
|
||||
"iconPath": "static/image/cat.png",
|
||||
"selectedIconPath": "static/image/cat-active.png"
|
||||
},
|
||||
{
|
||||
"pagePath": "pages/cart/cart",
|
||||
"text": "Cart",
|
||||
"iconPath": "static/image/cart.png",
|
||||
"selectedIconPath": "static/image/cart-active.png"
|
||||
},
|
||||
{
|
||||
"pagePath": "pages/user/user",
|
||||
"text": "User",
|
||||
"iconPath": "static/image/user.png",
|
||||
"selectedIconPath": "static/image/user-active.png"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tab Bar Properties
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| color | HexColor | Unselected text color |
|
||||
| selectedColor | HexColor | Selected text color |
|
||||
| backgroundColor | HexColor | Background color |
|
||||
| borderStyle | String | black/white |
|
||||
| list | Array | Tab items (2-5 items) |
|
||||
| position | String | bottom/top |
|
||||
|
||||
### Tab Item Properties
|
||||
|
||||
| Property | Type | Required | Description |
|
||||
|----------|------|----------|-------------|
|
||||
| pagePath | String | Yes | Page path |
|
||||
| text | String | Yes | Tab text |
|
||||
| iconPath | String | No | Icon path (81x81px) |
|
||||
| selectedIconPath | String | No | Selected icon |
|
||||
|
||||
### Custom Tab Bar (WeChat/QQ/Douyin)
|
||||
|
||||
```json
|
||||
{
|
||||
"tabBar": {
|
||||
"custom": true,
|
||||
"list": [
|
||||
{ "pagePath": "pages/index/index", "text": "Home" }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Create `custom-tab-bar/index` component in root.
|
||||
|
||||
## Sub-packages
|
||||
|
||||
Split app into smaller chunks for faster loading.
|
||||
|
||||
```json
|
||||
{
|
||||
"subPackages": [
|
||||
{
|
||||
"root": "packageA",
|
||||
"pages": [
|
||||
{ "path": "pages/cat/cat" },
|
||||
{ "path": "pages/dog/dog" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"root": "packageB",
|
||||
"pages": [
|
||||
{ "path": "pages/apple/apple" },
|
||||
{ "path": "pages/banana/banana" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"preloadRule": {
|
||||
"pages/index/index": {
|
||||
"network": "all",
|
||||
"packages": ["packageA"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## EasyCom (Auto Component Import)
|
||||
|
||||
```json
|
||||
{
|
||||
"easycom": {
|
||||
"autoscan": true,
|
||||
"custom": {
|
||||
"^u--(.*)": "uview-plus/components/u-$1/u-$1.vue",
|
||||
"^up-(.*)": "uview-plus/components/u-$1/u-$1.vue",
|
||||
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With this config, components are auto-imported without registration.
|
||||
|
||||
## Conditional Compilation in Config
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [
|
||||
{
|
||||
"path": "pages/index/index",
|
||||
"style": {
|
||||
"navigationBarTitleText": "Home"
|
||||
}
|
||||
}
|
||||
],
|
||||
"globalStyle": {
|
||||
"navigationBarTextStyle": "black"
|
||||
},
|
||||
"condition": {
|
||||
"current": 0,
|
||||
"list": [
|
||||
{
|
||||
"name": "test",
|
||||
"path": "pages/test/test",
|
||||
"query": "id=1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp-weixin": {
|
||||
"appid": "wx...",
|
||||
"setting": {
|
||||
"urlCheck": false
|
||||
}
|
||||
},
|
||||
"app-plus": {
|
||||
"splashscreen": {
|
||||
"alwaysShowBeforeRender": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/collocation/pages.md
|
||||
-->
|
||||
250
.claude/skills/uni-app/references/core-form-components.md
Normal file
250
.claude/skills/uni-app/references/core-form-components.md
Normal file
@@ -0,0 +1,250 @@
|
||||
---
|
||||
name: Form Components
|
||||
description: Input, selection, and form control components
|
||||
---
|
||||
|
||||
# Form Components
|
||||
|
||||
## input
|
||||
|
||||
Single-line text input.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<input
|
||||
v-model="inputValue"
|
||||
type="text"
|
||||
placeholder="Enter text"
|
||||
:maxlength="100"
|
||||
:focus="true"
|
||||
@input="onInput"
|
||||
@focus="onFocus"
|
||||
@blur="onBlur"
|
||||
@confirm="onConfirm"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| value | String | | Input value |
|
||||
| type | String | text | Input type: text/number/idcard/digit/tel |
|
||||
| password | Boolean | false | Password input |
|
||||
| placeholder | String | | Placeholder text |
|
||||
| placeholder-style | String | | Placeholder inline styles |
|
||||
| placeholder-class | String | | Placeholder CSS class |
|
||||
| maxlength | Number | 140 | Max character length |
|
||||
| cursor-spacing | Number | 0 | Cursor distance from keyboard bottom (px) |
|
||||
| focus | Boolean | false | Auto focus |
|
||||
| confirm-type | String | done | Return key type: send/search/next/go/done |
|
||||
| confirm-hold | Boolean | false | Keep keyboard open after confirm |
|
||||
|
||||
**Events:**
|
||||
- `@input` - Input value change
|
||||
- `@focus` - Input focused
|
||||
- `@blur` - Input blurred
|
||||
- `@confirm` - Confirm button clicked
|
||||
- `@keyboardheightchange` - Keyboard height changed
|
||||
|
||||
## textarea
|
||||
|
||||
Multi-line text input.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<textarea
|
||||
v-model="content"
|
||||
placeholder="Enter content"
|
||||
:maxlength="500"
|
||||
:auto-height="true"
|
||||
:show-confirm-bar="false"
|
||||
@linechange="onLineChange"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Additional Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| auto-height | Boolean | false | Auto adjust height |
|
||||
| fixed | Boolean | false | Fixed position when scrolling |
|
||||
| cursor | Number | | Cursor position |
|
||||
| show-confirm-bar | Boolean | true | Show recommendation bar (WeChat) |
|
||||
| selection-start | Number | -1 | Selection start position |
|
||||
| selection-end | Number | -1 | Selection end position |
|
||||
|
||||
## picker
|
||||
|
||||
Selection from predefined options.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Selector mode -->
|
||||
<picker mode="selector" :range="options" :value="selected" @change="onChange">
|
||||
<view>Selected: {{ options[selected] }}</view>
|
||||
</picker>
|
||||
|
||||
<!-- Multi-selector -->
|
||||
<picker mode="multiSelector" :range="multiOptions" @change="onMultiChange">
|
||||
<view>Multi-select</view>
|
||||
</picker>
|
||||
|
||||
<!-- Date picker -->
|
||||
<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="onDateChange">
|
||||
<view>Date: {{ date }}</view>
|
||||
</picker>
|
||||
|
||||
<!-- Region picker -->
|
||||
<picker mode="region" :value="region" @change="onRegionChange">
|
||||
<view>Region: {{ region.join('-') }}</view>
|
||||
</picker>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
options: ['Option 1', 'Option 2', 'Option 3'],
|
||||
selected: 0,
|
||||
multiOptions: [['A', 'B'], ['1', '2', '3']],
|
||||
date: '2024-01-01',
|
||||
startDate: '2020-01-01',
|
||||
endDate: '2025-12-31',
|
||||
region: ['Beijing', 'Beijing', 'Dongcheng']
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
onChange(e) {
|
||||
this.selected = e.detail.value
|
||||
},
|
||||
onDateChange(e) {
|
||||
this.date = e.detail.value
|
||||
},
|
||||
onRegionChange(e) {
|
||||
this.region = e.detail.value
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Mode-specific Properties:**
|
||||
|
||||
| Mode | Properties |
|
||||
|------|------------|
|
||||
| selector | range, range-key |
|
||||
| multiSelector | range, range-key |
|
||||
| time | start, end |
|
||||
| date | start, end, fields (year/month/day) |
|
||||
| region | custom-item, disable-sub-districts |
|
||||
|
||||
## picker-view
|
||||
|
||||
Embedded picker view (inline, not popup).
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<picker-view :value="value" @change="onChange">
|
||||
<picker-view-column>
|
||||
<view v-for="item in years" :key="item">{{ item }}年</view>
|
||||
</picker-view-column>
|
||||
<picker-view-column>
|
||||
<view v-for="item in months" :key="item">{{ item }}月</view>
|
||||
</picker-view-column>
|
||||
</picker-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## radio / checkbox
|
||||
|
||||
Selection controls.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Radio group -->
|
||||
<radio-group @change="onRadioChange">
|
||||
<label v-for="item in items" :key="item.value">
|
||||
<radio :value="item.value" :checked="item.checked" color="#007AFF" />
|
||||
{{ item.name }}
|
||||
</label>
|
||||
</radio-group>
|
||||
|
||||
<!-- Checkbox group -->
|
||||
<checkbox-group @change="onCheckboxChange">
|
||||
<label v-for="item in items" :key="item.value">
|
||||
<checkbox :value="item.value" :checked="item.checked" color="#007AFF" />
|
||||
{{ item.name }}
|
||||
</label>
|
||||
</checkbox-group>
|
||||
</template>
|
||||
```
|
||||
|
||||
**radio/checkbox Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| value | String | | Identifier value |
|
||||
| checked | Boolean | false | Selected state |
|
||||
| disabled | Boolean | false | Disabled state |
|
||||
| color | Color | | Selected color |
|
||||
|
||||
## switch
|
||||
|
||||
Toggle switch.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<switch
|
||||
:checked="isOn"
|
||||
:disabled="false"
|
||||
type="switch"
|
||||
color="#007AFF"
|
||||
@change="onSwitchChange"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| checked | Boolean | false | Checked state |
|
||||
| disabled | Boolean | false | Disabled state |
|
||||
| type | String | switch | Style: switch/checkbox |
|
||||
| color | Color | | Switch color when on |
|
||||
|
||||
## slider
|
||||
|
||||
Range slider input.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<slider
|
||||
:value="50"
|
||||
:min="0"
|
||||
:max="100"
|
||||
:step="1"
|
||||
:show-value="true"
|
||||
:disabled="false"
|
||||
activeColor="#007AFF"
|
||||
backgroundColor="#e9e9e9"
|
||||
block-size="28"
|
||||
@change="onChange"
|
||||
@changing="onChanging"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/input.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/textarea.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/picker.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/radio.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/checkbox.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/switch.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/slider.md
|
||||
-->
|
||||
133
.claude/skills/uni-app/references/core-framework.md
Normal file
133
.claude/skills/uni-app/references/core-framework.md
Normal file
@@ -0,0 +1,133 @@
|
||||
---
|
||||
name: Core Framework
|
||||
description: UniApp core framework concepts, project structure, and platform overview
|
||||
---
|
||||
|
||||
# UniApp Core Framework
|
||||
|
||||
UniApp is a Vue.js-based cross-platform framework for developing applications that run on iOS, Android, HarmonyOS, Web, and various mini-program platforms (WeChat, Alipay, Baidu, Douyin, etc.).
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── pages/ # Page files
|
||||
│ └── index/
|
||||
│ └── index.vue # Page component
|
||||
├── components/ # Reusable components
|
||||
├── static/ # Static assets (images, fonts)
|
||||
├── App.vue # Application root component
|
||||
├── main.js # Application entry
|
||||
├── manifest.json # App configuration
|
||||
├── pages.json # Page routing config
|
||||
└── uni.scss # Global SCSS variables
|
||||
```
|
||||
|
||||
## Platform Support
|
||||
|
||||
| Platform | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| App | APP-PLUS | iOS/Android native apps |
|
||||
| App nvue | APP-PLUS-NVUE | Native rendering pages |
|
||||
| H5 | H5 / WEB | Web applications |
|
||||
| WeChat Mini Program | MP-WEIXIN | WeChat MP |
|
||||
| Alipay | MP-ALIPAY | Alipay MP |
|
||||
| Baidu | MP-BAIDU | Baidu Smart Program |
|
||||
| Douyin | MP-TOUTIAO | ByteDance MP |
|
||||
| QQ | MP-QQ | QQ Mini Program |
|
||||
| Kuaishou | MP-KUAISHOU | Kuaishou MP |
|
||||
| HarmonyOS | APP-HARMONY | HarmonyOS Next |
|
||||
|
||||
## Condition Compilation
|
||||
|
||||
Handle platform differences using special comment syntax:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<view>
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<text>App only content</text>
|
||||
<!-- #endif -->
|
||||
|
||||
<!-- #ifdef MP-WEIXIN -->
|
||||
<text>WeChat MP only</text>
|
||||
<!-- #endif -->
|
||||
|
||||
<!-- #ifndef H5 -->
|
||||
<text>All platforms except H5</text>
|
||||
<!-- #endif -->
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
methods: {
|
||||
getPlatform() {
|
||||
// #ifdef APP-PLUS
|
||||
return 'App'
|
||||
// #endif
|
||||
// #ifdef H5
|
||||
return 'Web'
|
||||
// #endif
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* #ifdef APP-PLUS */
|
||||
.app-style { padding: 20px; }
|
||||
/* #endif */
|
||||
</style>
|
||||
```
|
||||
|
||||
## Platform Values Reference
|
||||
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| VUE3 / VUE2 | Vue version |
|
||||
| UNI-APP-X | UniApp X project |
|
||||
| APP-PLUS | App (JS engine) |
|
||||
| APP-PLUS-NVUE / APP-NVUE | App nvue pages |
|
||||
| APP-ANDROID | Android platform |
|
||||
| APP-IOS | iOS platform |
|
||||
| APP-HARMONY | HarmonyOS Next |
|
||||
| H5 / WEB | Web platform |
|
||||
| MP-WEIXIN | WeChat Mini Program |
|
||||
| MP-ALIPAY | Alipay Mini Program |
|
||||
| MP-BAIDU | Baidu Smart Program |
|
||||
| MP-TOUTIAO | Douyin Mini Program |
|
||||
| MP-LARK | Feishu Mini Program |
|
||||
| MP-QQ | QQ Mini Program |
|
||||
| MP-KUAISHOU | Kuaishou Mini Program |
|
||||
| MP-HARMONY | HarmonyOS Meta Service |
|
||||
|
||||
## API Promise Support
|
||||
|
||||
UniApp APIs support Promise when no callback is provided:
|
||||
|
||||
```javascript
|
||||
// Promise style
|
||||
uni.request({ url: 'https://api.example.com' })
|
||||
.then(res => console.log(res))
|
||||
.catch(err => console.error(err))
|
||||
|
||||
// Async/await
|
||||
async function fetchData() {
|
||||
try {
|
||||
const res = await uni.request({ url: 'https://api.example.com' })
|
||||
return res.data
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Synchronous APIs (ending in `Sync`), `create*` methods, and `*Manager` methods do not support Promise.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/README.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/tutorial/platform.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/README.md
|
||||
-->
|
||||
202
.claude/skills/uni-app/references/core-view-components.md
Normal file
202
.claude/skills/uni-app/references/core-view-components.md
Normal file
@@ -0,0 +1,202 @@
|
||||
---
|
||||
name: View Components
|
||||
description: Core container components for layout and structure
|
||||
---
|
||||
|
||||
# View Components
|
||||
|
||||
## view
|
||||
|
||||
Basic container component, similar to HTML `<div>`.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<view class="container">
|
||||
<view class="flex-row">
|
||||
<view class="item">A</view>
|
||||
<view class="item">B</view>
|
||||
</view>
|
||||
<view class="flex-column">
|
||||
<view class="item">C</view>
|
||||
<view class="item">D</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| hover-class | String | none | CSS class when pressed |
|
||||
| hover-stop-propagation | Boolean | false | Stop propagation to ancestor nodes |
|
||||
| hover-start-time | Number | 50 | Delay before hover state (ms) |
|
||||
| hover-stay-time | Number | 400 | Duration to keep hover state (ms) |
|
||||
|
||||
**Tips:**
|
||||
- `<div>` is auto-converted to `<view>` in mini-programs
|
||||
- Use `<text>` to wrap text in nvue pages
|
||||
|
||||
## scroll-view
|
||||
|
||||
Scrollable container with enhanced scroll capabilities.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Vertical scroll -->
|
||||
<scroll-view
|
||||
scroll-y
|
||||
class="scroll-container"
|
||||
@scroll="onScroll"
|
||||
@scrolltolower="loadMore"
|
||||
:scroll-top="scrollTop"
|
||||
:scroll-into-view="targetId"
|
||||
>
|
||||
<view id="item1">Item 1</view>
|
||||
<view id="item2">Item 2</view>
|
||||
</scroll-view>
|
||||
|
||||
<!-- Horizontal scroll -->
|
||||
<scroll-view scroll-x class="horizontal-scroll">
|
||||
<view class="scroll-item">1</view>
|
||||
<view class="scroll-item">2</view>
|
||||
</scroll-view>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| scroll-x | Boolean | Enable horizontal scroll |
|
||||
| scroll-y | Boolean | Enable vertical scroll |
|
||||
| upper-threshold | Number | Distance from top to trigger scrolltoupper (px) |
|
||||
| lower-threshold | Number | Distance from bottom to trigger scrolltolower (px) |
|
||||
| scroll-top | Number | Vertical scroll position |
|
||||
| scroll-left | Number | Horizontal scroll position |
|
||||
| scroll-into-view | String | Element ID to scroll into view |
|
||||
| scroll-with-animation | Boolean | Enable smooth scroll animation |
|
||||
| enable-back-to-top | Boolean | iOS: tap status bar to scroll top |
|
||||
|
||||
**Events:**
|
||||
- `@scroll` - Scroll event
|
||||
- `@scrolltoupper` - Reached top
|
||||
- `@scrolltolower` - Reached bottom
|
||||
|
||||
## swiper
|
||||
|
||||
Carousel/slider container for switching content.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<swiper
|
||||
:current="currentIndex"
|
||||
:autoplay="true"
|
||||
:interval="3000"
|
||||
:duration="500"
|
||||
:circular="true"
|
||||
:indicator-dots="true"
|
||||
@change="onSwiperChange"
|
||||
>
|
||||
<swiper-item>
|
||||
<view class="slide">Slide 1</view>
|
||||
</swiper-item>
|
||||
<swiper-item>
|
||||
<view class="slide">Slide 2</view>
|
||||
</swiper-item>
|
||||
</swiper>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
currentIndex: 0
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
onSwiperChange(e) {
|
||||
this.currentIndex = e.detail.current
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**swiper Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| indicator-dots | Boolean | false | Show pagination dots |
|
||||
| indicator-color | Color | rgba(0,0,0,.3) | Inactive dot color |
|
||||
| indicator-active-color | Color | #000000 | Active dot color |
|
||||
| autoplay | Boolean | false | Auto-play slides |
|
||||
| current | Number | 0 | Current slide index |
|
||||
| interval | Number | 5000 | Auto-play interval (ms) |
|
||||
| duration | Number | 500 | Transition duration (ms) |
|
||||
| circular | Boolean | false | Circular sliding |
|
||||
| vertical | Boolean | false | Vertical sliding |
|
||||
| previous-margin | String | 0px | Previous slide margin |
|
||||
| next-margin | String | 0px | Next slide margin |
|
||||
|
||||
## movable-area / movable-view
|
||||
|
||||
Draggable and scalable container.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<movable-area class="move-area">
|
||||
<movable-view
|
||||
:x="x"
|
||||
:y="y"
|
||||
direction="all"
|
||||
:scale="true"
|
||||
:scale-min="0.5"
|
||||
:scale-max="4"
|
||||
@change="onChange"
|
||||
@scale="onScale"
|
||||
>
|
||||
Draggable content
|
||||
</movable-view>
|
||||
</movable-area>
|
||||
</template>
|
||||
```
|
||||
|
||||
**movable-view Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| direction | String | none | Move direction: all/vertical/horizontal/none |
|
||||
| x | Number | | Initial X position |
|
||||
| y | Number | | Initial Y position |
|
||||
| scale | Boolean | false | Enable scaling |
|
||||
| scale-min | Number | 0.5 | Min scale |
|
||||
| scale-max | Number | 10 | Max scale |
|
||||
| scale-value | Number | 1 | Initial scale |
|
||||
|
||||
## cover-view / cover-image
|
||||
|
||||
Native overlay components that can cover native components (map, video, canvas).
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<map class="map">
|
||||
<cover-view class="overlay">Overlay text</cover-view>
|
||||
<cover-image class="marker" src="/static/marker.png" />
|
||||
</map>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Limitations:**
|
||||
- Only supported in WeChat MP, App, and H5
|
||||
- Limited styling capabilities
|
||||
- Cannot nest regular components inside
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/view.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/scroll-view.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/swiper.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/movable-area.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/cover-view.md
|
||||
-->
|
||||
391
.claude/skills/uni-app/references/feature-file-operations.md
Normal file
391
.claude/skills/uni-app/references/feature-file-operations.md
Normal file
@@ -0,0 +1,391 @@
|
||||
---
|
||||
name: File Operations
|
||||
description: File system operations, image/video selection, and file management
|
||||
---
|
||||
|
||||
# File Operations
|
||||
|
||||
## Image Selection
|
||||
|
||||
### uni.chooseImage
|
||||
|
||||
Select images from album or camera.
|
||||
|
||||
```javascript
|
||||
// Select from album
|
||||
uni.chooseImage({
|
||||
count: 9, // Max 9
|
||||
sizeType: ['original', 'compressed'],
|
||||
sourceType: ['album'],
|
||||
success: (res) => {
|
||||
console.log('Selected:', res.tempFilePaths)
|
||||
// tempFilePaths: ['blob:xxx', 'blob:xxx']
|
||||
// tempFiles: [{ path, size }]
|
||||
}
|
||||
})
|
||||
|
||||
// Take photo
|
||||
uni.chooseImage({
|
||||
count: 1,
|
||||
sourceType: ['camera'],
|
||||
success: (res) => {
|
||||
const tempPath = res.tempFilePaths[0]
|
||||
this.uploadImage(tempPath)
|
||||
}
|
||||
})
|
||||
|
||||
// Both album and camera
|
||||
uni.chooseImage({
|
||||
count: 5,
|
||||
sizeType: ['compressed'], // Compressed only
|
||||
sourceType: ['album', 'camera'],
|
||||
success: (res) => {
|
||||
res.tempFilePaths.forEach(path => {
|
||||
this.previewImage(path)
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| count | Number | 9 | Max number of images |
|
||||
| sizeType | Array | ['original', 'compressed'] | original/compressed |
|
||||
| sourceType | Array | ['album', 'camera'] | album/camera |
|
||||
|
||||
## Video Selection
|
||||
|
||||
### uni.chooseVideo
|
||||
|
||||
Select or record video.
|
||||
|
||||
```javascript
|
||||
uni.chooseVideo({
|
||||
sourceType: ['album', 'camera'],
|
||||
compressed: true,
|
||||
maxDuration: 60,
|
||||
camera: 'back', // front/back
|
||||
success: (res) => {
|
||||
console.log('Path:', res.tempFilePath)
|
||||
console.log('Duration:', res.duration) // seconds
|
||||
console.log('Size:', res.size) // bytes
|
||||
console.log('Height:', res.height)
|
||||
console.log('Width:', res.width)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### uni.chooseMedia (WeChat/QQ)
|
||||
|
||||
Choose mixed media types.
|
||||
|
||||
```javascript
|
||||
uni.chooseMedia({
|
||||
count: 9,
|
||||
mediaType: ['image', 'video'],
|
||||
sourceType: ['album', 'camera'],
|
||||
maxDuration: 30,
|
||||
camera: 'back',
|
||||
success: (res) => {
|
||||
console.log(res.tempFiles)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## File Selection
|
||||
|
||||
### uni.chooseFile
|
||||
|
||||
Select any file type.
|
||||
|
||||
```javascript
|
||||
uni.chooseFile({
|
||||
count: 1,
|
||||
type: 'all', // all/video/image/file
|
||||
extension: ['.pdf', '.doc', '.docx'], // Filter by extension
|
||||
success: (res) => {
|
||||
console.log(res.tempFilePaths)
|
||||
console.log(res.tempFiles)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## File System Operations (App)
|
||||
|
||||
### Get File System Manager
|
||||
|
||||
```javascript
|
||||
const fs = uni.getFileSystemManager()
|
||||
```
|
||||
|
||||
### Read File
|
||||
|
||||
```javascript
|
||||
// Read as text
|
||||
fs.readFile({
|
||||
filePath: `${uni.env.USER_DATA_PATH}/data.txt`,
|
||||
encoding: 'utf8',
|
||||
success: (res) => {
|
||||
console.log(res.data)
|
||||
}
|
||||
})
|
||||
|
||||
// Read as binary
|
||||
fs.readFile({
|
||||
filePath: tempFilePath,
|
||||
encoding: 'binary',
|
||||
success: (res) => {
|
||||
console.log(res.data)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Write File
|
||||
|
||||
```javascript
|
||||
fs.writeFile({
|
||||
filePath: `${uni.env.USER_DATA_PATH}/config.json`,
|
||||
data: JSON.stringify({ theme: 'dark' }),
|
||||
encoding: 'utf8',
|
||||
success: () => {
|
||||
console.log('File written')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Append to File
|
||||
|
||||
```javascript
|
||||
fs.appendFile({
|
||||
filePath: `${uni.env.USER_DATA_PATH}/log.txt`,
|
||||
data: '\nNew log entry',
|
||||
encoding: 'utf8',
|
||||
success: () => {
|
||||
console.log('Appended')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Delete File
|
||||
|
||||
```javascript
|
||||
fs.unlink({
|
||||
filePath: `${uni.env.USER_DATA_PATH}/temp.txt`,
|
||||
success: () => {
|
||||
console.log('File deleted')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Check File Exists
|
||||
|
||||
```javascript
|
||||
fs.access({
|
||||
path: `${uni.env.USER_DATA_PATH}/data.json`,
|
||||
success: () => {
|
||||
console.log('File exists')
|
||||
},
|
||||
fail: () => {
|
||||
console.log('File not found')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Create Directory
|
||||
|
||||
```javascript
|
||||
fs.mkdir({
|
||||
dirPath: `${uni.env.USER_DATA_PATH}/downloads`,
|
||||
recursive: true, // Create parent directories
|
||||
success: () => {
|
||||
console.log('Directory created')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Read Directory
|
||||
|
||||
```javascript
|
||||
fs.readdir({
|
||||
dirPath: `${uni.env.USER_DATA_PATH}/downloads`,
|
||||
success: (res) => {
|
||||
console.log('Files:', res.files)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Get File Info
|
||||
|
||||
```javascript
|
||||
fs.getFileInfo({
|
||||
filePath: tempFilePath,
|
||||
success: (res) => {
|
||||
console.log('Size:', res.size)
|
||||
console.log('Create time:', res.createTime)
|
||||
console.log('Last access:', res.lastAccessedTime)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Save and Open Files
|
||||
|
||||
### Save File
|
||||
|
||||
```javascript
|
||||
uni.saveFile({
|
||||
tempFilePath: res.tempFilePath,
|
||||
success: (res) => {
|
||||
const savedPath = res.savedFilePath
|
||||
console.log('Saved to:', savedPath)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Get Saved File List
|
||||
|
||||
```javascript
|
||||
uni.getSavedFileList({
|
||||
success: (res) => {
|
||||
console.log('Files:', res.fileList)
|
||||
// [{ filePath, createTime, size }, ...]
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Get Saved File Info
|
||||
|
||||
```javascript
|
||||
uni.getSavedFileInfo({
|
||||
filePath: savedFilePath,
|
||||
success: (res) => {
|
||||
console.log('Size:', res.size)
|
||||
console.log('Create time:', res.createTime)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Remove Saved File
|
||||
|
||||
```javascript
|
||||
uni.removeSavedFile({
|
||||
filePath: savedFilePath,
|
||||
success: () => {
|
||||
console.log('File removed')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Open Document
|
||||
|
||||
```javascript
|
||||
uni.openDocument({
|
||||
filePath: filePath,
|
||||
fileType: 'pdf', // Optional hint
|
||||
showMenu: true, // Show share menu (WeChat)
|
||||
success: () => {
|
||||
console.log('Document opened')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Image Operations
|
||||
|
||||
### Preview Image
|
||||
|
||||
```javascript
|
||||
uni.previewImage({
|
||||
current: currentImage, // Current image URL
|
||||
urls: imageList, // All image URLs
|
||||
indicator: 'default',
|
||||
loop: false,
|
||||
longPressActions: {
|
||||
itemList: ['Save Image', 'Share'],
|
||||
success: (data) => {
|
||||
console.log('Selected:', data.tapIndex)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Get Image Info
|
||||
|
||||
```javascript
|
||||
uni.getImageInfo({
|
||||
src: imagePath,
|
||||
success: (res) => {
|
||||
console.log('Width:', res.width)
|
||||
console.log('Height:', res.height)
|
||||
console.log('Path:', res.path)
|
||||
console.log('Orientation:', res.orientation)
|
||||
console.log('Type:', res.type)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Compress Image
|
||||
|
||||
```javascript
|
||||
uni.compressImage({
|
||||
src: originalPath,
|
||||
quality: 80, // 0-100
|
||||
success: (res) => {
|
||||
console.log('Compressed:', res.tempFilePath)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Save Image to Album
|
||||
|
||||
```javascript
|
||||
uni.saveImageToPhotosAlbum({
|
||||
filePath: tempFilePath,
|
||||
success: () => {
|
||||
uni.showToast({ title: 'Saved to album' })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Video Operations
|
||||
|
||||
### Save Video to Album
|
||||
|
||||
```javascript
|
||||
uni.saveVideoToPhotosAlbum({
|
||||
filePath: videoPath,
|
||||
success: () => {
|
||||
uni.showToast({ title: 'Video saved' })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Get Video Info
|
||||
|
||||
```javascript
|
||||
uni.getVideoInfo({
|
||||
src: videoPath,
|
||||
success: (res) => {
|
||||
console.log('Duration:', res.duration)
|
||||
console.log('Size:', res.size)
|
||||
console.log('Bitrate:', res.bitrate)
|
||||
console.log('FPS:', res.fps)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## File Paths Reference
|
||||
|
||||
| Path Type | Example | Description |
|
||||
|-----------|---------|-------------|
|
||||
| tempFilePath | `blob:xxx` or `_doc/uniapp_temp/xxx` | Temporary file |
|
||||
| savedFilePath | `_doc/uniapp_save/xxx` | Saved file |
|
||||
| USER_DATA_PATH | `_doc/` | App data directory |
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/media/image.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/media/file.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/file/file.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/file/getFileSystemManager.md
|
||||
-->
|
||||
423
.claude/skills/uni-app/references/feature-lifecycle.md
Normal file
423
.claude/skills/uni-app/references/feature-lifecycle.md
Normal file
@@ -0,0 +1,423 @@
|
||||
---
|
||||
name: Page Lifecycle
|
||||
description: Page and application lifecycle hooks
|
||||
---
|
||||
|
||||
# Page Lifecycle
|
||||
|
||||
## Application Lifecycle
|
||||
|
||||
In `App.vue`:
|
||||
|
||||
```javascript
|
||||
export default {
|
||||
globalData: {
|
||||
userInfo: null,
|
||||
theme: 'light'
|
||||
},
|
||||
|
||||
onLaunch(options) {
|
||||
// App launched (only once)
|
||||
console.log('App launched', options)
|
||||
this.checkUpdate()
|
||||
},
|
||||
|
||||
onShow(options) {
|
||||
// App shown/foreground
|
||||
console.log('App shown', options)
|
||||
},
|
||||
|
||||
onHide() {
|
||||
// App hidden/background
|
||||
console.log('App hidden')
|
||||
},
|
||||
|
||||
onError(msg) {
|
||||
// Global error handler
|
||||
console.error('App error:', msg)
|
||||
},
|
||||
|
||||
onUnhandledRejection(err) {
|
||||
// Unhandled promise rejection
|
||||
console.error('Unhandled rejection:', err)
|
||||
},
|
||||
|
||||
onPageNotFound(res) {
|
||||
// 404 page not found
|
||||
console.error('Page not found:', res.path)
|
||||
uni.redirectTo({
|
||||
url: '/pages/404/404'
|
||||
})
|
||||
},
|
||||
|
||||
methods: {
|
||||
checkUpdate() {
|
||||
// Check for app updates
|
||||
const updateManager = uni.getUpdateManager()
|
||||
updateManager.onCheckForUpdate((res) => {
|
||||
if (res.hasUpdate) {
|
||||
console.log('New version available')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Page Lifecycle
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
// === Page Load ===
|
||||
onLoad(options) {
|
||||
// Page loaded with query parameters
|
||||
console.log('Page loaded', options)
|
||||
// options contains URL query params
|
||||
// e.g., /pages/detail?id=123 -> options = { id: '123' }
|
||||
this.id = options.id
|
||||
this.loadData()
|
||||
},
|
||||
|
||||
// === Page Show ===
|
||||
onShow() {
|
||||
// Page shown (every time)
|
||||
console.log('Page shown')
|
||||
// Good for refreshing data when returning
|
||||
},
|
||||
|
||||
// === Page Ready ===
|
||||
onReady() {
|
||||
// Page ready, DOM rendered
|
||||
console.log('Page ready')
|
||||
// Safe to access DOM elements
|
||||
this.initChart()
|
||||
},
|
||||
|
||||
// === Page Hide ===
|
||||
onHide() {
|
||||
// Page hidden (navigated away)
|
||||
console.log('Page hidden')
|
||||
// Pause videos, timers, etc.
|
||||
},
|
||||
|
||||
// === Page Unload ===
|
||||
onUnload() {
|
||||
// Page destroyed
|
||||
console.log('Page unloaded')
|
||||
// Clean up resources, remove listeners
|
||||
clearInterval(this.timer)
|
||||
},
|
||||
|
||||
// === Pull Down Refresh ===
|
||||
onPullDownRefresh() {
|
||||
// User pulled down
|
||||
console.log('Pull down refresh')
|
||||
this.refreshData().finally(() => {
|
||||
uni.stopPullDownRefresh()
|
||||
})
|
||||
},
|
||||
|
||||
// === Reach Bottom ===
|
||||
onReachBottom() {
|
||||
// Scrolled to bottom
|
||||
console.log('Reach bottom')
|
||||
this.loadMore()
|
||||
},
|
||||
|
||||
// === Page Scroll ===
|
||||
onPageScroll(e) {
|
||||
// Page scrolled
|
||||
// e.scrollTop: scroll position
|
||||
this.scrollTop = e.scrollTop
|
||||
},
|
||||
|
||||
// === Resize ===
|
||||
onResize(e) {
|
||||
// Page resized (e.g., rotation)
|
||||
console.log('Page resized', e.size)
|
||||
},
|
||||
|
||||
// === Share ===
|
||||
onShareAppMessage(res) {
|
||||
// Native share (MP)
|
||||
if (res.from === 'button') {
|
||||
// From share button
|
||||
console.log(res.target)
|
||||
}
|
||||
return {
|
||||
title: 'Share Title',
|
||||
path: '/pages/index/index',
|
||||
imageUrl: '/static/share.png'
|
||||
}
|
||||
},
|
||||
|
||||
// === Timeline Share ===
|
||||
onShareTimeline() {
|
||||
// Share to timeline (WeChat)
|
||||
return {
|
||||
title: 'Timeline Title',
|
||||
query: 'id=123',
|
||||
imageUrl: '/static/share.png'
|
||||
}
|
||||
},
|
||||
|
||||
// === Add to Favorites ===
|
||||
onAddToFavorites() {
|
||||
// Add to MP favorites
|
||||
return {
|
||||
title: 'Favorite Title',
|
||||
imageUrl: '/static/fav.png',
|
||||
query: 'id=123'
|
||||
}
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
id: null,
|
||||
scrollTop: 0,
|
||||
timer: null
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
loadData() {
|
||||
// Load page data
|
||||
},
|
||||
refreshData() {
|
||||
// Refresh data
|
||||
},
|
||||
loadMore() {
|
||||
// Load more data
|
||||
},
|
||||
initChart() {
|
||||
// Initialize chart after DOM ready
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Component Lifecycle (Vue 2)
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
// === Creation ===
|
||||
beforeCreate() {
|
||||
// Instance initialized
|
||||
},
|
||||
|
||||
created() {
|
||||
// Instance created, data observed
|
||||
// Good for initial data loading
|
||||
},
|
||||
|
||||
// === Mounting ===
|
||||
beforeMount() {
|
||||
// Before DOM mount
|
||||
},
|
||||
|
||||
mounted() {
|
||||
// DOM mounted
|
||||
// Good for DOM operations
|
||||
},
|
||||
|
||||
// === Updating ===
|
||||
beforeUpdate() {
|
||||
// Before data update
|
||||
},
|
||||
|
||||
updated() {
|
||||
// After data update
|
||||
},
|
||||
|
||||
// === Destruction ===
|
||||
beforeDestroy() {
|
||||
// Before instance destroyed
|
||||
// Clean up here
|
||||
},
|
||||
|
||||
destroyed() {
|
||||
// Instance destroyed
|
||||
},
|
||||
|
||||
// === Keep-alive ===
|
||||
activated() {
|
||||
// Component activated (kept-alive)
|
||||
},
|
||||
|
||||
deactivated() {
|
||||
// Component deactivated (kept-alive)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Component Lifecycle (Vue 3)
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import {
|
||||
onBeforeMount,
|
||||
onMounted,
|
||||
onBeforeUpdate,
|
||||
onUpdated,
|
||||
onBeforeUnmount,
|
||||
onUnmounted,
|
||||
onActivated,
|
||||
onDeactivated
|
||||
} from 'vue'
|
||||
|
||||
// Setup runs before beforeCreate
|
||||
console.log('setup')
|
||||
|
||||
onBeforeMount(() => {
|
||||
console.log('onBeforeMount')
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
console.log('onMounted')
|
||||
})
|
||||
|
||||
onBeforeUpdate(() => {
|
||||
console.log('onBeforeUpdate')
|
||||
})
|
||||
|
||||
onUpdated(() => {
|
||||
console.log('onUpdated')
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
console.log('onBeforeUnmount')
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
console.log('onUnmounted')
|
||||
})
|
||||
|
||||
onActivated(() => {
|
||||
console.log('onActivated')
|
||||
})
|
||||
|
||||
onDeactivated(() => {
|
||||
console.log('onDeactivated')
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Lifecycle Comparison
|
||||
|
||||
| Scenario | UniApp Page | Vue Component |
|
||||
|----------|-------------|---------------|
|
||||
| Initial load | onLoad | created |
|
||||
| DOM ready | onReady | mounted |
|
||||
| Page show | onShow | - |
|
||||
| Page hide | onHide | - |
|
||||
| Page destroy | onUnload | destroyed/unmounted |
|
||||
| Data refresh | onPullDownRefresh | - |
|
||||
| Infinite scroll | onReachBottom | - |
|
||||
| Scroll position | onPageScroll | - |
|
||||
|
||||
## App Update Manager
|
||||
|
||||
```javascript
|
||||
// In App.vue onLaunch
|
||||
onLaunch() {
|
||||
const updateManager = uni.getUpdateManager()
|
||||
|
||||
updateManager.onCheckForUpdate((res) => {
|
||||
console.log('Has update:', res.hasUpdate)
|
||||
})
|
||||
|
||||
updateManager.onUpdateReady(() => {
|
||||
uni.showModal({
|
||||
title: 'Update Ready',
|
||||
content: 'New version downloaded. Restart to apply?',
|
||||
success: (res) => {
|
||||
if (res.confirm) {
|
||||
updateManager.applyUpdate()
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
updateManager.onUpdateFailed(() => {
|
||||
console.error('Update failed')
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Data Loading Pattern
|
||||
|
||||
```javascript
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
loading: false,
|
||||
error: null,
|
||||
data: null
|
||||
}
|
||||
},
|
||||
|
||||
onLoad(options) {
|
||||
this.fetchData(options.id)
|
||||
},
|
||||
|
||||
onPullDownRefresh() {
|
||||
this.fetchData(this.id).finally(() => {
|
||||
uni.stopPullDownRefresh()
|
||||
})
|
||||
},
|
||||
|
||||
methods: {
|
||||
async fetchData(id) {
|
||||
this.loading = true
|
||||
this.error = null
|
||||
try {
|
||||
this.data = await api.getDetail(id)
|
||||
} catch (err) {
|
||||
this.error = err.message
|
||||
} finally {
|
||||
this.loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Scroll Performance
|
||||
|
||||
```javascript
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
scrollTop: 0,
|
||||
showBackTop: false
|
||||
}
|
||||
},
|
||||
|
||||
// Throttle scroll events
|
||||
onPageScroll: throttle(function(e) {
|
||||
this.scrollTop = e.scrollTop
|
||||
this.showBackTop = e.scrollTop > 500
|
||||
}, 200),
|
||||
|
||||
methods: {
|
||||
scrollToTop() {
|
||||
uni.pageScrollTo({
|
||||
scrollTop: 0,
|
||||
duration: 300
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/collocation/App.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/lifecycle.md
|
||||
-->
|
||||
417
.claude/skills/uni-app/references/feature-location.md
Normal file
417
.claude/skills/uni-app/references/feature-location.md
Normal file
@@ -0,0 +1,417 @@
|
||||
---
|
||||
name: Location Services
|
||||
description: Geolocation, map operations, and location-based services
|
||||
---
|
||||
|
||||
# Location Services
|
||||
|
||||
## Get Current Location
|
||||
|
||||
### uni.getLocation
|
||||
|
||||
Get current geographic location.
|
||||
|
||||
```javascript
|
||||
uni.getLocation({
|
||||
type: 'wgs84', // wgs84/gcj02 (gcj02 for map display)
|
||||
altitude: false, // Include altitude
|
||||
geocode: false, // Include address info (App)
|
||||
highAccuracyExpireTime: 3000, // High accuracy timeout
|
||||
success: (res) => {
|
||||
console.log('Latitude:', res.latitude)
|
||||
console.log('Longitude:', res.longitude)
|
||||
console.log('Speed:', res.speed)
|
||||
console.log('Accuracy:', res.accuracy)
|
||||
// App only:
|
||||
console.log('Altitude:', res.altitude)
|
||||
console.log('Address:', res.address)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('Location failed:', err)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Response Properties:**
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| latitude | Number | Latitude |
|
||||
| longitude | Number | Longitude |
|
||||
| speed | Number | Speed (m/s) |
|
||||
| accuracy | Number | Accuracy (meters) |
|
||||
| altitude | Number | Altitude (meters) |
|
||||
| verticalAccuracy | Number | Vertical accuracy |
|
||||
| horizontalAccuracy | Number | Horizontal accuracy |
|
||||
| address | Object | Address info (App) |
|
||||
|
||||
### uni.getFuzzyLocation (WeChat)
|
||||
|
||||
Get approximate location (better privacy, faster).
|
||||
|
||||
```javascript
|
||||
uni.getFuzzyLocation({
|
||||
type: 'wgs84',
|
||||
success: (res) => {
|
||||
console.log(res.latitude, res.longitude)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Choose Location
|
||||
|
||||
### uni.chooseLocation
|
||||
|
||||
Open map to select location.
|
||||
|
||||
```javascript
|
||||
uni.chooseLocation({
|
||||
latitude: 39.9,
|
||||
longitude: 116.4,
|
||||
keyword: 'restaurant',
|
||||
success: (res) => {
|
||||
console.log('Name:', res.name)
|
||||
console.log('Address:', res.address)
|
||||
console.log('Latitude:', res.latitude)
|
||||
console.log('Longitude:', res.longitude)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Open Location
|
||||
|
||||
### uni.openLocation
|
||||
|
||||
Open external map app.
|
||||
|
||||
```javascript
|
||||
uni.openLocation({
|
||||
latitude: 39.9,
|
||||
longitude: 116.4,
|
||||
name: 'Destination Name',
|
||||
address: 'Full address here',
|
||||
scale: 18
|
||||
})
|
||||
```
|
||||
|
||||
## Location Change Monitoring
|
||||
|
||||
### uni.startLocationUpdate
|
||||
|
||||
Start background location updates.
|
||||
|
||||
```javascript
|
||||
uni.startLocationUpdate({
|
||||
type: 'gcj02',
|
||||
success: () => {
|
||||
console.log('Location updates started')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### uni.startLocationUpdateBackground
|
||||
|
||||
Start background location (requires permission).
|
||||
|
||||
```javascript
|
||||
uni.startLocationUpdateBackground({
|
||||
type: 'gcj02',
|
||||
success: () => {
|
||||
console.log('Background location started')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Listen for Location Changes
|
||||
|
||||
```javascript
|
||||
uni.onLocationChange((res) => {
|
||||
console.log('Location updated:', res.latitude, res.longitude)
|
||||
})
|
||||
|
||||
// Stop listening
|
||||
uni.offLocationChange(callback)
|
||||
```
|
||||
|
||||
### Stop Location Updates
|
||||
|
||||
```javascript
|
||||
uni.stopLocationUpdate({
|
||||
success: () => {
|
||||
console.log('Location updates stopped')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Map Component
|
||||
|
||||
### Basic Map
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<map
|
||||
id="myMap"
|
||||
style="width: 100%; height: 300px;"
|
||||
:latitude="latitude"
|
||||
:longitude="longitude"
|
||||
:scale="14"
|
||||
:markers="markers"
|
||||
:polyline="polyline"
|
||||
:circles="circles"
|
||||
:show-location="true"
|
||||
@markertap="onMarkerTap"
|
||||
@regionchange="onRegionChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
latitude: 39.909,
|
||||
longitude: 116.39742,
|
||||
markers: [{
|
||||
id: 1,
|
||||
latitude: 39.909,
|
||||
longitude: 116.39742,
|
||||
title: 'Marker 1',
|
||||
iconPath: '/static/marker.png',
|
||||
width: 30,
|
||||
height: 30,
|
||||
callout: {
|
||||
content: 'Hello',
|
||||
color: '#000',
|
||||
fontSize: 14,
|
||||
borderRadius: 5,
|
||||
padding: 10,
|
||||
display: 'BYCLICK'
|
||||
}
|
||||
}],
|
||||
polyline: [{
|
||||
points: [
|
||||
{ latitude: 39.909, longitude: 116.39742 },
|
||||
{ latitude: 39.91, longitude: 116.4 }
|
||||
],
|
||||
color: '#FF0000',
|
||||
width: 2,
|
||||
dottedLine: false
|
||||
}],
|
||||
circles: [{
|
||||
latitude: 39.909,
|
||||
longitude: 116.39742,
|
||||
radius: 100,
|
||||
strokeWidth: 2,
|
||||
fillColor: '#FF000020'
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### Map Context Operations
|
||||
|
||||
```javascript
|
||||
export default {
|
||||
onReady() {
|
||||
this.mapContext = uni.createMapContext('myMap')
|
||||
},
|
||||
|
||||
methods: {
|
||||
// Get center location
|
||||
getCenter() {
|
||||
this.mapContext.getCenterLocation({
|
||||
success: (res) => {
|
||||
console.log('Center:', res.latitude, res.longitude)
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
// Move to location
|
||||
moveToLocation() {
|
||||
this.mapContext.moveToLocation({
|
||||
latitude: 39.9,
|
||||
longitude: 116.4
|
||||
})
|
||||
},
|
||||
|
||||
// Translate marker
|
||||
translateMarker() {
|
||||
this.mapContext.translateMarker({
|
||||
markerId: 1,
|
||||
destination: {
|
||||
latitude: 39.91,
|
||||
longitude: 116.41
|
||||
},
|
||||
autoRotate: true,
|
||||
rotate: 0,
|
||||
duration: 1000
|
||||
})
|
||||
},
|
||||
|
||||
// Include points in view
|
||||
includePoints() {
|
||||
this.mapContext.includePoints({
|
||||
points: [
|
||||
{ latitude: 39.9, longitude: 116.4 },
|
||||
{ latitude: 39.91, longitude: 116.41 }
|
||||
],
|
||||
padding: [10, 10, 10, 10]
|
||||
})
|
||||
},
|
||||
|
||||
// Get region
|
||||
getRegion() {
|
||||
this.mapContext.getRegion({
|
||||
success: (res) => {
|
||||
console.log('Southwest:', res.southwest)
|
||||
console.log('Northeast:', res.northeast)
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
// Add markers
|
||||
addMarkers() {
|
||||
this.mapContext.addMarkers({
|
||||
markers: [{
|
||||
id: 2,
|
||||
latitude: 39.91,
|
||||
longitude: 116.41,
|
||||
title: 'New Marker'
|
||||
}],
|
||||
clear: false // Don't clear existing
|
||||
})
|
||||
},
|
||||
|
||||
// Remove markers
|
||||
removeMarkers() {
|
||||
this.mapContext.removeMarkers({
|
||||
markerIds: [1, 2]
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Coordinate Systems
|
||||
|
||||
| System | Description | Usage |
|
||||
|--------|-------------|-------|
|
||||
| WGS84 | GPS coordinates | International standard |
|
||||
| GCJ02 | Mars coordinates | China national standard |
|
||||
| BD09 | Baidu coordinates | Baidu Map only |
|
||||
|
||||
**Note:** For map display in China, use `gcj02`.
|
||||
|
||||
## Permission Configuration
|
||||
|
||||
### Mini-Program
|
||||
|
||||
Add to `manifest.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mp-weixin": {
|
||||
"permission": {
|
||||
"scope.userLocation": {
|
||||
"desc": "Your location is needed to find nearby stores"
|
||||
}
|
||||
},
|
||||
"requiredPrivateInfos": [
|
||||
"getLocation",
|
||||
"chooseLocation"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### App (Android)
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"distribute": {
|
||||
"android": {
|
||||
"permissions": [
|
||||
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />",
|
||||
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### App (iOS)
|
||||
|
||||
```json
|
||||
{
|
||||
"app-plus": {
|
||||
"distribute": {
|
||||
"ios": {
|
||||
"privacyDescription": {
|
||||
"NSLocationWhenInUseUsageDescription": "Location is needed to find nearby stores",
|
||||
"NSLocationAlwaysUsageDescription": "Background location is needed for navigation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Permission Handling
|
||||
|
||||
```javascript
|
||||
async function getLocationWithPermission() {
|
||||
try {
|
||||
// Check permission
|
||||
const setting = await uni.getSetting()
|
||||
if (!setting.authSetting['scope.userLocation']) {
|
||||
// Request permission
|
||||
await uni.authorize({ scope: 'scope.userLocation' })
|
||||
}
|
||||
|
||||
// Get location
|
||||
const res = await uni.getLocation({ type: 'gcj02' })
|
||||
return res
|
||||
} catch (err) {
|
||||
if (err.errMsg.includes('auth deny')) {
|
||||
uni.showModal({
|
||||
title: 'Permission Required',
|
||||
content: 'Please enable location permission in settings',
|
||||
success: (res) => {
|
||||
if (res.confirm) {
|
||||
uni.openSetting()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Distance Calculation
|
||||
|
||||
```javascript
|
||||
function calculateDistance(lat1, lon1, lat2, lon2) {
|
||||
const R = 6371 // Earth's radius in km
|
||||
const dLat = (lat2 - lat1) * Math.PI / 180
|
||||
const dLon = (lon2 - lon1) * Math.PI / 180
|
||||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
||||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||||
Math.sin(dLon/2) * Math.sin(dLon/2)
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
|
||||
return R * c // Distance in km
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/location/location.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/location/location-change.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/location/open-location.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/map.md
|
||||
-->
|
||||
314
.claude/skills/uni-app/references/feature-media-components.md
Normal file
314
.claude/skills/uni-app/references/feature-media-components.md
Normal file
@@ -0,0 +1,314 @@
|
||||
---
|
||||
name: Media Components
|
||||
description: Image, video, audio, and camera components
|
||||
---
|
||||
|
||||
# Media Components
|
||||
|
||||
## image
|
||||
|
||||
Display images with various mode options.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Basic usage -->
|
||||
<image src="/static/logo.png" mode="aspectFit" />
|
||||
|
||||
<!-- With event handling -->
|
||||
<image
|
||||
:src="imageUrl"
|
||||
mode="aspectFill"
|
||||
:lazy-load="true"
|
||||
:show-menu-by-longpress="true"
|
||||
@load="onImageLoad"
|
||||
@error="onImageError"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| src | String | | Image source URL |
|
||||
| mode | String | scaleToFill | Display mode (see below) |
|
||||
| lazy-load | Boolean | false | Lazy load image |
|
||||
| show-menu-by-longpress | Boolean | false | Show menu on long press |
|
||||
| webp | Boolean | false | Parse WebP format (Android) |
|
||||
|
||||
**Mode Values:**
|
||||
|
||||
| Mode | Description |
|
||||
|------|-------------|
|
||||
| scaleToFill | Fill container, may distort |
|
||||
| aspectFit | Contain within container |
|
||||
| aspectFill | Cover container, may clip |
|
||||
| widthFix | Width fixed, height auto |
|
||||
| heightFix | Height fixed, width auto |
|
||||
| top / bottom / center / left / right | Align to position |
|
||||
| top left / top right / bottom left / bottom right | Corner alignment |
|
||||
|
||||
**Events:**
|
||||
- `@load` - Image loaded successfully
|
||||
- `@error` - Image failed to load
|
||||
|
||||
## video
|
||||
|
||||
Video player component.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<video
|
||||
id="myVideo"
|
||||
src="https://example.com/video.mp4"
|
||||
:controls="true"
|
||||
:autoplay="false"
|
||||
:loop="false"
|
||||
:muted="false"
|
||||
initial-time="30"
|
||||
:duration="300"
|
||||
poster="/static/poster.jpg"
|
||||
object-fit="contain"
|
||||
@play="onPlay"
|
||||
@pause="onPause"
|
||||
@ended="onEnded"
|
||||
@timeupdate="onTimeUpdate"
|
||||
@fullscreenchange="onFullscreenChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
onReady() {
|
||||
this.videoContext = uni.createVideoContext('myVideo')
|
||||
},
|
||||
methods: {
|
||||
play() {
|
||||
this.videoContext.play()
|
||||
},
|
||||
pause() {
|
||||
this.videoContext.pause()
|
||||
},
|
||||
seek(time) {
|
||||
this.videoContext.seek(time)
|
||||
},
|
||||
sendDanmu(danmu) {
|
||||
this.videoContext.sendDanmu({
|
||||
text: danmu.text,
|
||||
color: danmu.color
|
||||
})
|
||||
},
|
||||
playbackRate(rate) {
|
||||
this.videoContext.playbackRate(rate)
|
||||
},
|
||||
onFullscreenChange(e) {
|
||||
console.log('Fullscreen:', e.detail.fullScreen)
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| src | String | | Video source URL |
|
||||
| controls | Boolean | true | Show controls |
|
||||
| autoplay | Boolean | false | Auto play |
|
||||
| loop | Boolean | false | Loop playback |
|
||||
| muted | Boolean | false | Muted |
|
||||
| initial-time | Number | 0 | Start time (s) |
|
||||
| duration | Number | | Total duration (s) |
|
||||
| poster | String | | Poster image URL |
|
||||
| object-fit | String | contain | contain/cover/fill |
|
||||
| danmu-list | Array | | Danmu list |
|
||||
| danmu-btn | Boolean | false | Show danmu button |
|
||||
| enable-danmu | Boolean | false | Enable danmu |
|
||||
| show-center-play-btn | Boolean | true | Show center play button |
|
||||
| show-play-btn | Boolean | true | Show play button |
|
||||
| show-fullscreen-btn | Boolean | true | Show fullscreen button |
|
||||
| page-gesture | Boolean | false | Enable page gesture |
|
||||
| enable-progress-gesture | Boolean | true | Enable progress gesture |
|
||||
|
||||
## audio
|
||||
|
||||
Audio player (deprecated, use `uni.getBackgroundAudioManager` instead).
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<audio
|
||||
:src="audioSrc"
|
||||
:poster="posterUrl"
|
||||
:name="audioName"
|
||||
:author="author"
|
||||
:controls="true"
|
||||
:loop="false"
|
||||
@play="onPlay"
|
||||
@pause="onPause"
|
||||
@ended="onEnded"
|
||||
@timeupdate="onTimeUpdate"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
## camera
|
||||
|
||||
Camera component for capturing photos/videos.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<camera
|
||||
device-position="back"
|
||||
flash="auto"
|
||||
resolution="high"
|
||||
frame-size="large"
|
||||
@stop="onCameraStop"
|
||||
@error="onCameraError"
|
||||
@initdone="onCameraReady"
|
||||
/>
|
||||
<button @click="takePhoto">Take Photo</button>
|
||||
<button @click="startRecord">Start Record</button>
|
||||
<button @click="stopRecord">Stop Record</button>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
onReady() {
|
||||
this.cameraContext = uni.createCameraContext()
|
||||
},
|
||||
methods: {
|
||||
takePhoto() {
|
||||
this.cameraContext.takePhoto({
|
||||
quality: 'high',
|
||||
success: (res) => {
|
||||
console.log(res.tempImagePath)
|
||||
}
|
||||
})
|
||||
},
|
||||
startRecord() {
|
||||
this.cameraContext.startRecord({
|
||||
success: () => console.log('Recording started')
|
||||
})
|
||||
},
|
||||
stopRecord() {
|
||||
this.cameraContext.stopRecord({
|
||||
success: (res) => {
|
||||
console.log(res.tempVideoPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| mode | String | normal | normal/scanCode |
|
||||
| resolution | String | medium | low/medium/high |
|
||||
| device-position | String | back | front/back |
|
||||
| flash | String | auto | auto/on/off |
|
||||
| frame-size | String | large | small/medium/large |
|
||||
|
||||
## live-player / live-pusher
|
||||
|
||||
Live streaming components (mini-program only).
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Live player -->
|
||||
<live-player
|
||||
src="rtmp://example.com/live/stream"
|
||||
mode="live"
|
||||
:autoplay="true"
|
||||
:muted="false"
|
||||
orientation="vertical"
|
||||
object-fit="contain"
|
||||
@statechange="onStateChange"
|
||||
@error="onError"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
## map
|
||||
|
||||
Map component for displaying maps and markers.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<map
|
||||
id="myMap"
|
||||
style="width: 100%; height: 300px;"
|
||||
:latitude="latitude"
|
||||
:longitude="longitude"
|
||||
:scale="14"
|
||||
:markers="markers"
|
||||
:polyline="polyline"
|
||||
:circles="circles"
|
||||
:controls="controls"
|
||||
:show-location="true"
|
||||
@markertap="onMarkerTap"
|
||||
@regionchange="onRegionChange"
|
||||
@tap="onMapTap"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
latitude: 39.909,
|
||||
longitude: 116.39742,
|
||||
markers: [{
|
||||
id: 1,
|
||||
latitude: 39.909,
|
||||
longitude: 116.39742,
|
||||
title: 'Marker 1',
|
||||
iconPath: '/static/marker.png',
|
||||
width: 30,
|
||||
height: 30
|
||||
}],
|
||||
polyline: [{
|
||||
points: [
|
||||
{ latitude: 39.909, longitude: 116.39742 },
|
||||
{ latitude: 39.91, longitude: 116.4 }
|
||||
],
|
||||
color: '#FF0000',
|
||||
width: 2
|
||||
}]
|
||||
}
|
||||
},
|
||||
onReady() {
|
||||
this.mapContext = uni.createMapContext('myMap')
|
||||
},
|
||||
methods: {
|
||||
moveToLocation() {
|
||||
this.mapContext.moveToLocation({
|
||||
latitude: 39.91,
|
||||
longitude: 116.4
|
||||
})
|
||||
},
|
||||
getCenterLocation() {
|
||||
this.mapContext.getCenterLocation({
|
||||
success: (res) => {
|
||||
console.log(res.latitude, res.longitude)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/image.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/video.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/audio.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/camera.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/live-player.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/map.md
|
||||
-->
|
||||
257
.claude/skills/uni-app/references/feature-navigation.md
Normal file
257
.claude/skills/uni-app/references/feature-navigation.md
Normal file
@@ -0,0 +1,257 @@
|
||||
---
|
||||
name: Navigation
|
||||
description: Navigation, routing, and page navigation components
|
||||
---
|
||||
|
||||
# Navigation
|
||||
|
||||
## navigator
|
||||
|
||||
Page navigation component.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Basic navigation -->
|
||||
<navigator url="/pages/detail/detail" hover-class="navigator-hover">
|
||||
Go to Detail
|
||||
</navigator>
|
||||
|
||||
<!-- Open in new page -->
|
||||
<navigator url="/pages/detail/detail" open-type="navigate">
|
||||
Navigate (default)
|
||||
</navigator>
|
||||
|
||||
<!-- Redirect (no back button) -->
|
||||
<navigator url="/pages/login/login" open-type="redirect">
|
||||
Login (redirect)
|
||||
</navigator>
|
||||
|
||||
<!-- Switch to tab page -->
|
||||
<navigator url="/pages/index/index" open-type="switchTab">
|
||||
Go to Home
|
||||
</navigator>
|
||||
|
||||
<!-- Re-launch app -->
|
||||
<navigator url="/pages/start/start" open-type="reLaunch">
|
||||
Restart
|
||||
</navigator>
|
||||
|
||||
<!-- Navigate back -->
|
||||
<navigator open-type="navigateBack" :delta="1">
|
||||
Go Back
|
||||
</navigator>
|
||||
|
||||
<!-- Exit app (mini-program) -->
|
||||
<navigator open-type="exit" target="miniProgram">
|
||||
Exit
|
||||
</navigator>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| url | String | | Target page path |
|
||||
| open-type | String | navigate | navigate/redirect/switchTab/reLaunch/navigateBack/exit |
|
||||
| delta | Number | 1 | Back level when open-type is navigateBack |
|
||||
| hover-class | String | navigator-hover | Hover state class |
|
||||
| hover-stop-propagation | Boolean | false | Stop hover propagation |
|
||||
| target | String | self | self/miniProgram (mini-program only) |
|
||||
|
||||
## Programmatic Navigation
|
||||
|
||||
### uni.navigateTo
|
||||
|
||||
Navigate to new page.
|
||||
|
||||
```javascript
|
||||
// Basic navigation
|
||||
uni.navigateTo({
|
||||
url: '/pages/detail/detail'
|
||||
})
|
||||
|
||||
// With query parameters
|
||||
uni.navigateTo({
|
||||
url: '/pages/detail/detail?id=123&name=test'
|
||||
})
|
||||
|
||||
// With events (Vue 2 only)
|
||||
uni.navigateTo({
|
||||
url: '/pages/detail/detail',
|
||||
events: {
|
||||
acceptDataFromOpenedPage(data) {
|
||||
console.log(data)
|
||||
}
|
||||
},
|
||||
success(res) {
|
||||
res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### uni.redirectTo
|
||||
|
||||
Redirect to new page (closes current page).
|
||||
|
||||
```javascript
|
||||
uni.redirectTo({
|
||||
url: '/pages/login/login'
|
||||
})
|
||||
```
|
||||
|
||||
### uni.reLaunch
|
||||
|
||||
Re-launch application to specified page.
|
||||
|
||||
```javascript
|
||||
uni.reLaunch({
|
||||
url: '/pages/index/index'
|
||||
})
|
||||
```
|
||||
|
||||
### uni.switchTab
|
||||
|
||||
Switch to tab bar page.
|
||||
|
||||
```javascript
|
||||
uni.switchTab({
|
||||
url: '/pages/home/home'
|
||||
})
|
||||
```
|
||||
|
||||
### uni.navigateBack
|
||||
|
||||
Navigate back to previous page.
|
||||
|
||||
```javascript
|
||||
// Go back one page
|
||||
uni.navigateBack()
|
||||
|
||||
// Go back multiple pages
|
||||
uni.navigateBack({
|
||||
delta: 2
|
||||
})
|
||||
|
||||
// With animation (App only)
|
||||
uni.navigateBack({
|
||||
delta: 1,
|
||||
animationType: 'pop-out',
|
||||
animationDuration: 300
|
||||
})
|
||||
```
|
||||
|
||||
### uni.preloadPage
|
||||
|
||||
Preload page for faster navigation (App only).
|
||||
|
||||
```javascript
|
||||
uni.preloadPage({
|
||||
url: '/pages/detail/detail'
|
||||
})
|
||||
```
|
||||
|
||||
## Getting Page Information
|
||||
|
||||
### getCurrentPages
|
||||
|
||||
Get current page stack.
|
||||
|
||||
```javascript
|
||||
const pages = getCurrentPages()
|
||||
const currentPage = pages[pages.length - 1]
|
||||
console.log(currentPage.route) // Current page path
|
||||
```
|
||||
|
||||
### getApp
|
||||
|
||||
Get app instance.
|
||||
|
||||
```javascript
|
||||
const app = getApp()
|
||||
console.log(app.globalData)
|
||||
```
|
||||
|
||||
## Page Event Channel (Vue 2)
|
||||
|
||||
Communicate between pages using event channel.
|
||||
|
||||
```javascript
|
||||
// Page A: Open page B
|
||||
uni.navigateTo({
|
||||
url: '/pages/pageB/pageB',
|
||||
success(res) {
|
||||
// Listen for events from page B
|
||||
res.eventChannel.on('acceptDataFromPageB', (data) => {
|
||||
console.log(data)
|
||||
})
|
||||
// Send data to page B
|
||||
res.eventChannel.emit('acceptDataFromPageA', { data: 'hello' })
|
||||
}
|
||||
})
|
||||
|
||||
// Page B: Receive and send data
|
||||
export default {
|
||||
onLoad() {
|
||||
const eventChannel = this.getOpenerEventChannel()
|
||||
// Listen for events from page A
|
||||
eventChannel.on('acceptDataFromPageA', (data) => {
|
||||
console.log(data)
|
||||
})
|
||||
// Send data back to page A
|
||||
eventChannel.emit('acceptDataFromPageB', { data: 'world' })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Navigation Bar
|
||||
|
||||
### Custom Navigation Bar
|
||||
|
||||
Configure in `pages.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [{
|
||||
"path": "pages/index/index",
|
||||
"style": {
|
||||
"navigationStyle": "custom"
|
||||
}
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
### uni.setNavigationBarTitle
|
||||
|
||||
```javascript
|
||||
uni.setNavigationBarTitle({
|
||||
title: 'New Title'
|
||||
})
|
||||
```
|
||||
|
||||
### uni.setNavigationBarColor
|
||||
|
||||
```javascript
|
||||
uni.setNavigationBarColor({
|
||||
frontColor: '#ffffff',
|
||||
backgroundColor: '#000000',
|
||||
animation: {
|
||||
duration: 400,
|
||||
timingFunc: 'easeIn'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### uni.showNavigationBarLoading
|
||||
|
||||
```javascript
|
||||
uni.showNavigationBarLoading()
|
||||
// ...loading operation
|
||||
uni.hideNavigationBarLoading()
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/component/navigator.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/router.md
|
||||
-->
|
||||
345
.claude/skills/uni-app/references/feature-network.md
Normal file
345
.claude/skills/uni-app/references/feature-network.md
Normal file
@@ -0,0 +1,345 @@
|
||||
---
|
||||
name: Network Requests
|
||||
description: HTTP requests, file upload/download, and WebSocket
|
||||
---
|
||||
|
||||
# Network Requests
|
||||
|
||||
## uni.request
|
||||
|
||||
Make HTTP requests to backend APIs.
|
||||
|
||||
```javascript
|
||||
// GET request
|
||||
uni.request({
|
||||
url: 'https://api.example.com/data',
|
||||
method: 'GET',
|
||||
data: { id: 123 },
|
||||
header: {
|
||||
'content-type': 'application/json',
|
||||
'Authorization': 'Bearer token'
|
||||
},
|
||||
timeout: 30000,
|
||||
success: (res) => {
|
||||
console.log(res.data)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error(err)
|
||||
},
|
||||
complete: () => {
|
||||
console.log('Request complete')
|
||||
}
|
||||
})
|
||||
|
||||
// POST request with JSON
|
||||
uni.request({
|
||||
url: 'https://api.example.com/submit',
|
||||
method: 'POST',
|
||||
data: {
|
||||
name: 'John',
|
||||
age: 30
|
||||
},
|
||||
header: {
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
success: (res) => {
|
||||
if (res.statusCode === 200) {
|
||||
console.log('Success:', res.data)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Using Promise
|
||||
uni.request({
|
||||
url: 'https://api.example.com/data',
|
||||
method: 'GET'
|
||||
}).then(res => {
|
||||
console.log(res.data)
|
||||
}).catch(err => {
|
||||
console.error(err)
|
||||
})
|
||||
|
||||
// Async/await
|
||||
async function fetchData() {
|
||||
try {
|
||||
const res = await uni.request({
|
||||
url: 'https://api.example.com/data'
|
||||
})
|
||||
return res.data
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch:', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| url | String | Yes | Request URL |
|
||||
| data | Object/String/Array/ArrayBuffer | No | Request data |
|
||||
| header | Object | No | Request headers |
|
||||
| method | String | No | HTTP method (default: GET) |
|
||||
| timeout | Number | No | Timeout in ms (default: 60000) |
|
||||
| dataType | String | No | Response data type (default: json) |
|
||||
| responseType | String | No | Response type (default: text) |
|
||||
| sslVerify | Boolean | No | Verify SSL certificate (default: true) |
|
||||
|
||||
**Response Object:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
data: Object | String | ArrayBuffer, // Response data
|
||||
statusCode: Number, // HTTP status code
|
||||
header: Object, // Response headers
|
||||
cookies: Array // Response cookies
|
||||
}
|
||||
```
|
||||
|
||||
## uni.uploadFile
|
||||
|
||||
Upload files to server.
|
||||
|
||||
```javascript
|
||||
uni.chooseImage({
|
||||
count: 1,
|
||||
success: (chooseRes) => {
|
||||
const tempFilePath = chooseRes.tempFilePaths[0]
|
||||
|
||||
const uploadTask = uni.uploadFile({
|
||||
url: 'https://api.example.com/upload',
|
||||
filePath: tempFilePath,
|
||||
name: 'file',
|
||||
formData: {
|
||||
user: 'test',
|
||||
description: 'Image upload'
|
||||
},
|
||||
header: {
|
||||
'Authorization': 'Bearer token'
|
||||
},
|
||||
success: (res) => {
|
||||
console.log('Upload success:', JSON.parse(res.data))
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('Upload failed:', err)
|
||||
}
|
||||
})
|
||||
|
||||
// Track upload progress
|
||||
uploadTask.onProgressUpdate((res) => {
|
||||
console.log('Progress:', res.progress)
|
||||
console.log('Uploaded bytes:', res.totalBytesSent)
|
||||
console.log('Total bytes:', res.totalBytesExpectedToSend)
|
||||
})
|
||||
|
||||
// Abort upload if needed
|
||||
// uploadTask.abort()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Upload Task Methods:**
|
||||
- `onProgressUpdate(callback)` - Listen for progress updates
|
||||
- `abort()` - Cancel the upload
|
||||
- `offProgressUpdate(callback)` - Remove progress listener
|
||||
|
||||
## uni.downloadFile
|
||||
|
||||
Download files from server.
|
||||
|
||||
```javascript
|
||||
const downloadTask = uni.downloadFile({
|
||||
url: 'https://example.com/file.pdf',
|
||||
success: (res) => {
|
||||
if (res.statusCode === 200) {
|
||||
console.log('Downloaded to:', res.tempFilePath)
|
||||
|
||||
// Save to local (App only)
|
||||
uni.saveFile({
|
||||
tempFilePath: res.tempFilePath,
|
||||
success: (saveRes) => {
|
||||
console.log('Saved to:', saveRes.savedFilePath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Track download progress
|
||||
downloadTask.onProgressUpdate((res) => {
|
||||
console.log('Progress:', res.progress)
|
||||
})
|
||||
```
|
||||
|
||||
## WebSocket
|
||||
|
||||
Real-time bidirectional communication.
|
||||
|
||||
```javascript
|
||||
// Connect to WebSocket
|
||||
const socketTask = uni.connectSocket({
|
||||
url: 'wss://api.example.com/ws',
|
||||
protocols: ['protocol1'],
|
||||
header: {
|
||||
'Authorization': 'Bearer token'
|
||||
},
|
||||
success: () => {
|
||||
console.log('WebSocket connecting...')
|
||||
}
|
||||
})
|
||||
|
||||
// Listen for connection open
|
||||
uni.onSocketOpen((res) => {
|
||||
console.log('WebSocket connected')
|
||||
|
||||
// Send message
|
||||
uni.sendSocketMessage({
|
||||
data: JSON.stringify({
|
||||
type: 'message',
|
||||
content: 'Hello server'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Listen for messages
|
||||
uni.onSocketMessage((res) => {
|
||||
console.log('Received:', res.data)
|
||||
const data = JSON.parse(res.data)
|
||||
// Handle message...
|
||||
})
|
||||
|
||||
// Listen for errors
|
||||
uni.onSocketError((err) => {
|
||||
console.error('WebSocket error:', err)
|
||||
})
|
||||
|
||||
// Listen for close
|
||||
uni.onSocketClose((res) => {
|
||||
console.log('WebSocket closed:', res)
|
||||
})
|
||||
|
||||
// Close connection
|
||||
function closeSocket() {
|
||||
uni.closeSocket({
|
||||
code: 1000,
|
||||
reason: 'User logout',
|
||||
success: () => {
|
||||
console.log('Socket closed successfully')
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Socket Task Methods:**
|
||||
- `close(options)` - Close connection
|
||||
- `send(options)` - Send message
|
||||
- `onOpen(callback)` - Connection opened
|
||||
- `onMessage(callback)` - Message received
|
||||
- `onClose(callback)` - Connection closed
|
||||
- `onError(callback)` - Error occurred
|
||||
|
||||
## Request Interceptors
|
||||
|
||||
Use `uni.addInterceptor` to intercept requests.
|
||||
|
||||
```javascript
|
||||
// Add request interceptor
|
||||
uni.addInterceptor('request', {
|
||||
invoke(args) {
|
||||
// Before request
|
||||
console.log('Request:', args)
|
||||
|
||||
// Add auth token
|
||||
args.header = args.header || {}
|
||||
args.header.Authorization = `Bearer ${getToken()}`
|
||||
|
||||
return args
|
||||
},
|
||||
success(res) {
|
||||
// After success
|
||||
console.log('Response:', res)
|
||||
return res
|
||||
},
|
||||
fail(err) {
|
||||
// After failure
|
||||
console.error('Request failed:', err)
|
||||
return err
|
||||
},
|
||||
complete(res) {
|
||||
// Always executed
|
||||
console.log('Request complete')
|
||||
}
|
||||
})
|
||||
|
||||
// Remove interceptor
|
||||
uni.removeInterceptor('request')
|
||||
```
|
||||
|
||||
## Domain Configuration
|
||||
|
||||
### Mini-Program
|
||||
|
||||
Configure request domains in mini-program developer console:
|
||||
- `request` domain: For `uni.request`
|
||||
- `uploadFile` domain: For `uni.uploadFile`
|
||||
- `downloadFile` domain: For `uni.downloadFile`
|
||||
- `websocket` domain: For `uni.connectSocket`
|
||||
|
||||
### H5
|
||||
|
||||
H5 uses browser's same-origin policy. Configure CORS on server or use proxy in development.
|
||||
|
||||
```javascript
|
||||
// vite.config.js proxy configuration
|
||||
export default {
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'https://api.example.com',
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/api/, '')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
```javascript
|
||||
// Create a request wrapper
|
||||
const request = (options) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
...options,
|
||||
success: (res) => {
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
resolve(res.data)
|
||||
} else if (res.statusCode === 401) {
|
||||
// Handle unauthorized
|
||||
uni.redirectTo({ url: '/pages/login/login' })
|
||||
reject(new Error('Unauthorized'))
|
||||
} else {
|
||||
reject(new Error(res.data.message || 'Request failed'))
|
||||
}
|
||||
},
|
||||
fail: reject
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Usage
|
||||
const api = {
|
||||
getUser: () => request({ url: '/user' }),
|
||||
updateUser: (data) => request({ url: '/user', method: 'PUT', data })
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/request/request.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/request/network-file.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/request/websocket.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/interceptor.md
|
||||
-->
|
||||
279
.claude/skills/uni-app/references/feature-storage.md
Normal file
279
.claude/skills/uni-app/references/feature-storage.md
Normal file
@@ -0,0 +1,279 @@
|
||||
---
|
||||
name: Storage
|
||||
description: Local data storage and caching APIs
|
||||
---
|
||||
|
||||
# Storage
|
||||
|
||||
## Synchronous Storage (Recommended for small data)
|
||||
|
||||
### uni.setStorageSync
|
||||
|
||||
Store data synchronously.
|
||||
|
||||
```javascript
|
||||
// Store simple value
|
||||
uni.setStorageSync('username', 'John')
|
||||
|
||||
// Store object
|
||||
uni.setStorageSync('userInfo', {
|
||||
name: 'John',
|
||||
age: 30,
|
||||
email: 'john@example.com'
|
||||
})
|
||||
|
||||
// Store array
|
||||
uni.setStorageSync('tags', ['vue', 'uniapp', 'javascript'])
|
||||
```
|
||||
|
||||
### uni.getStorageSync
|
||||
|
||||
Retrieve data synchronously.
|
||||
|
||||
```javascript
|
||||
// Get simple value
|
||||
const username = uni.getStorageSync('username')
|
||||
console.log(username) // 'John'
|
||||
|
||||
// Get object
|
||||
const userInfo = uni.getStorageSync('userInfo')
|
||||
console.log(userInfo.name) // 'John'
|
||||
|
||||
// Check if exists
|
||||
const value = uni.getStorageSync('nonexistent')
|
||||
console.log(value) // '' (empty string if not found)
|
||||
```
|
||||
|
||||
### uni.removeStorageSync
|
||||
|
||||
Remove specific key.
|
||||
|
||||
```javascript
|
||||
uni.removeStorageSync('username')
|
||||
```
|
||||
|
||||
### uni.clearStorageSync
|
||||
|
||||
Clear all storage.
|
||||
|
||||
```javascript
|
||||
uni.clearStorageSync()
|
||||
```
|
||||
|
||||
## Asynchronous Storage (Recommended for large data)
|
||||
|
||||
### uni.setStorage
|
||||
|
||||
```javascript
|
||||
uni.setStorage({
|
||||
key: 'userData',
|
||||
data: {
|
||||
id: 123,
|
||||
preferences: { theme: 'dark', language: 'zh' }
|
||||
},
|
||||
success: () => {
|
||||
console.log('Storage saved')
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('Save failed:', err)
|
||||
}
|
||||
})
|
||||
|
||||
// Promise style
|
||||
uni.setStorage({
|
||||
key: 'config',
|
||||
data: { debug: true }
|
||||
}).then(() => {
|
||||
console.log('Config saved')
|
||||
})
|
||||
```
|
||||
|
||||
### uni.getStorage
|
||||
|
||||
```javascript
|
||||
uni.getStorage({
|
||||
key: 'userData',
|
||||
success: (res) => {
|
||||
console.log('Data:', res.data)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.log('Key not found')
|
||||
}
|
||||
})
|
||||
|
||||
// Promise style
|
||||
uni.getStorage({ key: 'userData' })
|
||||
.then(res => console.log(res.data))
|
||||
.catch(() => console.log('Not found'))
|
||||
```
|
||||
|
||||
### uni.removeStorage
|
||||
|
||||
```javascript
|
||||
uni.removeStorage({
|
||||
key: 'tempData',
|
||||
success: () => {
|
||||
console.log('Removed successfully')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### uni.getStorageInfo
|
||||
|
||||
Get storage information.
|
||||
|
||||
```javascript
|
||||
uni.getStorageInfo({
|
||||
success: (res) => {
|
||||
console.log('Keys:', res.keys)
|
||||
console.log('Current size:', res.currentSize, 'KB')
|
||||
console.log('Limit size:', res.limitSize, 'KB')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Storage Limits
|
||||
|
||||
| Platform | Limit |
|
||||
|----------|-------|
|
||||
| Mini Program | 10 MB (single) / 200+ MB total |
|
||||
| App | No hard limit (device dependent) |
|
||||
| H5 | ~5-10 MB (browser dependent) |
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Data Persistence Helper
|
||||
|
||||
```javascript
|
||||
const storage = {
|
||||
// Set with expiration (days)
|
||||
setWithExpiry(key, value, days) {
|
||||
const item = {
|
||||
value,
|
||||
expiry: Date.now() + days * 24 * 60 * 60 * 1000
|
||||
}
|
||||
uni.setStorageSync(key, item)
|
||||
},
|
||||
|
||||
// Get with expiration check
|
||||
getWithExpiry(key) {
|
||||
const item = uni.getStorageSync(key)
|
||||
if (!item) return null
|
||||
|
||||
if (Date.now() > item.expiry) {
|
||||
uni.removeStorageSync(key)
|
||||
return null
|
||||
}
|
||||
return item.value
|
||||
},
|
||||
|
||||
// Safe get with default
|
||||
get(key, defaultValue = null) {
|
||||
try {
|
||||
const value = uni.getStorageSync(key)
|
||||
return value !== '' ? value : defaultValue
|
||||
} catch (e) {
|
||||
return defaultValue
|
||||
}
|
||||
},
|
||||
|
||||
// Batch operations
|
||||
setBatch(data) {
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
uni.setStorageSync(key, value)
|
||||
})
|
||||
},
|
||||
|
||||
clear() {
|
||||
uni.clearStorageSync()
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
storage.setWithExpiry('token', 'abc123', 7) // Expires in 7 days
|
||||
const token = storage.getWithExpiry('token')
|
||||
```
|
||||
|
||||
### User Session Management
|
||||
|
||||
```javascript
|
||||
const session = {
|
||||
setToken(token) {
|
||||
uni.setStorageSync('access_token', token)
|
||||
},
|
||||
|
||||
getToken() {
|
||||
return uni.getStorageSync('access_token')
|
||||
},
|
||||
|
||||
clearToken() {
|
||||
uni.removeStorageSync('access_token')
|
||||
},
|
||||
|
||||
setUserInfo(info) {
|
||||
uni.setStorageSync('user_info', info)
|
||||
},
|
||||
|
||||
getUserInfo() {
|
||||
return uni.getStorageSync('user_info')
|
||||
},
|
||||
|
||||
isLoggedIn() {
|
||||
return !!this.getToken()
|
||||
},
|
||||
|
||||
clear() {
|
||||
this.clearToken()
|
||||
uni.removeStorageSync('user_info')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## File Storage (App only)
|
||||
|
||||
### Local File System
|
||||
|
||||
```javascript
|
||||
// Get file system manager
|
||||
const fs = uni.getFileSystemManager()
|
||||
|
||||
// Write file
|
||||
fs.writeFile({
|
||||
filePath: `${uni.env.USER_DATA_PATH}/data.json`,
|
||||
data: JSON.stringify({ name: 'test' }),
|
||||
encoding: 'utf8',
|
||||
success: () => console.log('File written')
|
||||
})
|
||||
|
||||
// Read file
|
||||
fs.readFile({
|
||||
filePath: `${uni.env.USER_DATA_PATH}/data.json`,
|
||||
encoding: 'utf8',
|
||||
success: (res) => {
|
||||
const data = JSON.parse(res.data)
|
||||
console.log(data)
|
||||
}
|
||||
})
|
||||
|
||||
// Check if file exists
|
||||
fs.access({
|
||||
path: `${uni.env.USER_DATA_PATH}/data.json`,
|
||||
success: () => console.log('File exists'),
|
||||
fail: () => console.log('File not found')
|
||||
})
|
||||
```
|
||||
|
||||
## Storage Comparison
|
||||
|
||||
| Method | Data Type | Size Limit | Async | Use Case |
|
||||
|--------|-----------|------------|-------|----------|
|
||||
| StorageSync | Any | ~10MB | No | Small config data |
|
||||
| Storage | Any | ~10MB | Yes | Large data objects |
|
||||
| File System | Binary/Text | Large | Yes | Files, images |
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/storage/storage.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/file/file.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/file/getFileSystemManager.md
|
||||
-->
|
||||
300
.claude/skills/uni-app/references/feature-system-info.md
Normal file
300
.claude/skills/uni-app/references/feature-system-info.md
Normal file
@@ -0,0 +1,300 @@
|
||||
---
|
||||
name: System Information
|
||||
description: Device info, system info, and environment detection APIs
|
||||
---
|
||||
|
||||
# System Information
|
||||
|
||||
## uni.getSystemInfo / getSystemInfoSync
|
||||
|
||||
Get device and system information.
|
||||
|
||||
```javascript
|
||||
// Synchronous (faster, recommended)
|
||||
const info = uni.getSystemInfoSync()
|
||||
console.log(info)
|
||||
|
||||
// Asynchronous
|
||||
uni.getSystemInfo({
|
||||
success: (res) => {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
|
||||
// Promise
|
||||
uni.getSystemInfo().then(res => {
|
||||
console.log(res)
|
||||
})
|
||||
```
|
||||
|
||||
### System Info Properties
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| brand | String | Device brand |
|
||||
| model | String | Device model |
|
||||
| pixelRatio | Number | Device pixel ratio |
|
||||
| screenWidth | Number | Screen width (px) |
|
||||
| screenHeight | Number | Screen height (px) |
|
||||
| windowWidth | Number | Window width (px) |
|
||||
| windowHeight | Number | Window height (px) |
|
||||
| statusBarHeight | Number | Status bar height (px) |
|
||||
| language | String | Language |
|
||||
| system | String | OS version |
|
||||
| version | String | WeChat/Runtime version |
|
||||
| platform | String | Platform: ios/android/windows/mac/devtools |
|
||||
| SDKVersion | String | Client base library version |
|
||||
| appId | String | App ID (DCloud) |
|
||||
| appName | String | App name |
|
||||
| appVersion | String | App version |
|
||||
| appCodeName | String | App code name |
|
||||
| uniPlatform | String | uni-app platform |
|
||||
| uniCompileVersion | String | Compilation version |
|
||||
| uniRuntimeVersion | String | Runtime version |
|
||||
| deviceId | String | Device ID |
|
||||
| deviceBrand | String | Device brand |
|
||||
| deviceModel | String | Device model |
|
||||
| deviceType | String | Device type: phone/pad |
|
||||
| osName | String | OS name |
|
||||
| osVersion | String | OS version |
|
||||
| osLanguage | String | OS language |
|
||||
| osTheme | String | OS theme: light/dark |
|
||||
| batteryLevel | Number | Battery level (0-100) |
|
||||
|
||||
## uni.getAppBaseInfo
|
||||
|
||||
Get app base information.
|
||||
|
||||
```javascript
|
||||
const info = uni.getAppBaseInfo()
|
||||
// Returns: appId, appName, appVersion, appVersionCode, etc.
|
||||
```
|
||||
|
||||
## uni.getDeviceInfo
|
||||
|
||||
Get device hardware information.
|
||||
|
||||
```javascript
|
||||
const info = uni.getDeviceInfo()
|
||||
// Returns: brand, model, deviceId, deviceBrand, deviceModel, deviceType
|
||||
```
|
||||
|
||||
## uni.getWindowInfo
|
||||
|
||||
Get window information.
|
||||
|
||||
```javascript
|
||||
const info = uni.getWindowInfo()
|
||||
// Returns: pixelRatio, screenWidth, screenHeight, windowWidth, windowHeight,
|
||||
// statusBarHeight, safeArea, screenTop
|
||||
```
|
||||
|
||||
## Safe Area
|
||||
|
||||
Handle notched devices and safe areas.
|
||||
|
||||
```javascript
|
||||
const info = uni.getSystemInfoSync()
|
||||
|
||||
// Safe area info
|
||||
const safeArea = info.safeArea
|
||||
console.log(safeArea) // { top, left, right, bottom, width, height }
|
||||
|
||||
// Check if device has notch (unsafe area at top)
|
||||
const hasNotch = info.safeAreaInsets && info.safeAreaInsets.top > 0
|
||||
```
|
||||
|
||||
### Safe Area CSS Variables (App/H5)
|
||||
|
||||
```css
|
||||
.safe-area-bottom {
|
||||
padding-bottom: constant(safe-area-inset-bottom); /* iOS 11.0 */
|
||||
padding-bottom: env(safe-area-inset-bottom); /* iOS 11.2+ */
|
||||
}
|
||||
```
|
||||
|
||||
## Network Status
|
||||
|
||||
### uni.getNetworkType
|
||||
|
||||
```javascript
|
||||
uni.getNetworkType({
|
||||
success: (res) => {
|
||||
// res.networkType: wifi/2g/3g/4g/5g/unknown/none
|
||||
console.log('Network:', res.networkType)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### uni.onNetworkStatusChange
|
||||
|
||||
```javascript
|
||||
// Listen for network changes
|
||||
uni.onNetworkStatusChange((res) => {
|
||||
console.log('Network type:', res.networkType)
|
||||
console.log('Is connected:', res.isConnected)
|
||||
})
|
||||
|
||||
// Remove listener
|
||||
uni.offNetworkStatusChange(callback)
|
||||
```
|
||||
|
||||
## Battery Info
|
||||
|
||||
### uni.getBatteryInfo
|
||||
|
||||
```javascript
|
||||
uni.getBatteryInfo({
|
||||
success: (res) => {
|
||||
console.log('Level:', res.level) // 0-100
|
||||
console.log('Is charging:', res.isCharging)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Device Orientation
|
||||
|
||||
### uni.onDeviceMotionChange
|
||||
|
||||
```javascript
|
||||
uni.startDeviceMotionListening({
|
||||
interval: 'normal', // game/ui/normal
|
||||
success: () => {
|
||||
uni.onDeviceMotionChange((res) => {
|
||||
console.log('Alpha:', res.alpha) // 0-360
|
||||
console.log('Beta:', res.beta) // -180 to 180
|
||||
console.log('Gamma:', res.gamma) // -90 to 90
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Stop listening
|
||||
uni.stopDeviceMotionListening()
|
||||
```
|
||||
|
||||
### Screen Orientation
|
||||
|
||||
```javascript
|
||||
// Get current orientation
|
||||
const info = uni.getSystemInfoSync()
|
||||
const isLandscape = info.screenWidth > info.screenHeight
|
||||
|
||||
// Lock orientation (App only)
|
||||
plus.screen.lockOrientation('portrait-primary')
|
||||
// Options: portrait-primary/portrait-secondary/landscape-primary/landscape-secondary
|
||||
```
|
||||
|
||||
## Screen Brightness
|
||||
|
||||
```javascript
|
||||
// Set brightness (0-1)
|
||||
uni.setScreenBrightness({
|
||||
value: 0.8
|
||||
})
|
||||
|
||||
// Get brightness
|
||||
uni.getScreenBrightness({
|
||||
success: (res) => {
|
||||
console.log('Brightness:', res.value)
|
||||
}
|
||||
})
|
||||
|
||||
// Keep screen on
|
||||
uni.setKeepScreenOn({
|
||||
keepScreenOn: true
|
||||
})
|
||||
```
|
||||
|
||||
## Vibration
|
||||
|
||||
```javascript
|
||||
// Short vibration (15ms)
|
||||
uni.vibrateShort()
|
||||
|
||||
// Long vibration (400ms)
|
||||
uni.vibrateLong()
|
||||
|
||||
// Pattern vibration (App only)
|
||||
uni.vibrateLong() // or custom pattern
|
||||
```
|
||||
|
||||
## Clipboard
|
||||
|
||||
```javascript
|
||||
// Set clipboard
|
||||
uni.setClipboardData({
|
||||
data: 'Text to copy',
|
||||
success: () => {
|
||||
uni.showToast({ title: 'Copied' })
|
||||
}
|
||||
})
|
||||
|
||||
// Get clipboard
|
||||
uni.getClipboardData({
|
||||
success: (res) => {
|
||||
console.log('Clipboard:', res.data)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Phone Call
|
||||
|
||||
```javascript
|
||||
uni.makePhoneCall({
|
||||
phoneNumber: '13800138000'
|
||||
})
|
||||
```
|
||||
|
||||
## Scan Code
|
||||
|
||||
```javascript
|
||||
uni.scanCode({
|
||||
onlyFromCamera: false, // Allow from album
|
||||
scanType: ['qrCode', 'barCode'], // Types to scan
|
||||
success: (res) => {
|
||||
console.log('Result:', res.result)
|
||||
console.log('Type:', res.scanType)
|
||||
console.log('CharSet:', res.charSet)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Platform Detection
|
||||
|
||||
```javascript
|
||||
const info = uni.getSystemInfoSync()
|
||||
|
||||
// Platform checks
|
||||
const isIOS = info.platform === 'ios'
|
||||
const isAndroid = info.platform === 'android'
|
||||
const isWindows = info.platform === 'windows'
|
||||
const isMac = info.platform === 'mac'
|
||||
const isDevtools = info.platform === 'devtools'
|
||||
|
||||
// App platform checks
|
||||
const isApp = info.uniPlatform === 'app'
|
||||
const isH5 = info.uniPlatform === 'web'
|
||||
const isWeixinMP = info.uniPlatform === 'mp-weixin'
|
||||
|
||||
// Safe area calculation
|
||||
const safeAreaTop = info.statusBarHeight + (isApp ? 44 : 0) // 44px for nav bar
|
||||
```
|
||||
|
||||
## Storage Info
|
||||
|
||||
```javascript
|
||||
uni.getStorageInfo({
|
||||
success: (res) => {
|
||||
console.log('Keys:', res.keys)
|
||||
console.log('Current size:', res.currentSize)
|
||||
console.log('Limit size:', res.limitSize)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/system/info.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/system/network.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/system/phone.md
|
||||
-->
|
||||
382
.claude/skills/uni-app/references/feature-ui-feedback.md
Normal file
382
.claude/skills/uni-app/references/feature-ui-feedback.md
Normal file
@@ -0,0 +1,382 @@
|
||||
---
|
||||
name: UI Feedback
|
||||
description: Toast, modal, loading, and action sheet APIs
|
||||
---
|
||||
|
||||
# UI Feedback
|
||||
|
||||
## Toast Messages
|
||||
|
||||
### uni.showToast
|
||||
|
||||
Display success/error messages.
|
||||
|
||||
```javascript
|
||||
// Success toast
|
||||
uni.showToast({
|
||||
title: 'Success!',
|
||||
icon: 'success',
|
||||
duration: 2000,
|
||||
mask: false
|
||||
})
|
||||
|
||||
// Loading toast
|
||||
uni.showToast({
|
||||
title: 'Loading...',
|
||||
icon: 'loading',
|
||||
duration: 10000
|
||||
})
|
||||
|
||||
// Text only (no icon)
|
||||
uni.showToast({
|
||||
title: 'Please wait',
|
||||
icon: 'none',
|
||||
duration: 2000
|
||||
})
|
||||
|
||||
// Error toast
|
||||
uni.showToast({
|
||||
title: 'Failed!',
|
||||
icon: 'error'
|
||||
})
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| title | String | Required | Message text |
|
||||
| icon | String | success | success/loading/none/error |
|
||||
| duration | Number | 1500 | Duration in ms |
|
||||
| mask | Boolean | false | Prevent touch during display |
|
||||
| position | String | | top/center/bottom (App) |
|
||||
|
||||
### uni.hideToast
|
||||
|
||||
```javascript
|
||||
uni.hideToast()
|
||||
```
|
||||
|
||||
## Loading
|
||||
|
||||
### uni.showLoading
|
||||
|
||||
```javascript
|
||||
uni.showLoading({
|
||||
title: 'Loading...',
|
||||
mask: true // Prevent interaction
|
||||
})
|
||||
|
||||
// Hide after operation
|
||||
setTimeout(() => {
|
||||
uni.hideLoading()
|
||||
}, 2000)
|
||||
```
|
||||
|
||||
### uni.hideLoading
|
||||
|
||||
```javascript
|
||||
uni.hideLoading()
|
||||
```
|
||||
|
||||
## Modal Dialogs
|
||||
|
||||
### uni.showModal
|
||||
|
||||
Alert and confirm dialogs.
|
||||
|
||||
```javascript
|
||||
// Alert (single button)
|
||||
uni.showModal({
|
||||
title: 'Notice',
|
||||
content: 'Operation completed',
|
||||
showCancel: false
|
||||
})
|
||||
|
||||
// Confirm (two buttons)
|
||||
uni.showModal({
|
||||
title: 'Confirm',
|
||||
content: 'Are you sure?',
|
||||
cancelText: 'Cancel',
|
||||
cancelColor: '#999',
|
||||
confirmText: 'Confirm',
|
||||
confirmColor: '#007AFF',
|
||||
success: (res) => {
|
||||
if (res.confirm) {
|
||||
console.log('User confirmed')
|
||||
} else if (res.cancel) {
|
||||
console.log('User cancelled')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Editable modal
|
||||
uni.showModal({
|
||||
title: 'Input',
|
||||
content: 'Enter your name',
|
||||
editable: true,
|
||||
placeholderText: 'Name',
|
||||
success: (res) => {
|
||||
if (res.confirm) {
|
||||
console.log('Input:', res.content)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Action Sheet
|
||||
|
||||
### uni.showActionSheet
|
||||
|
||||
Bottom action menu.
|
||||
|
||||
```javascript
|
||||
uni.showActionSheet({
|
||||
itemList: ['Take Photo', 'Choose from Album', 'Cancel'],
|
||||
itemColor: '#000000',
|
||||
success: (res) => {
|
||||
// res.tapIndex: 0, 1, 2...
|
||||
console.log('Selected:', res.tapIndex)
|
||||
switch (res.tapIndex) {
|
||||
case 0:
|
||||
this.takePhoto()
|
||||
break
|
||||
case 1:
|
||||
this.chooseFromAlbum()
|
||||
break
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
console.log('Cancelled')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Pull to Refresh
|
||||
|
||||
### Enable in pages.json
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [{
|
||||
"path": "pages/index/index",
|
||||
"style": {
|
||||
"enablePullDownRefresh": true,
|
||||
"backgroundTextStyle": "dark"
|
||||
}
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
### Handle in Page
|
||||
|
||||
```javascript
|
||||
export default {
|
||||
onPullDownRefresh() {
|
||||
console.log('Pull down triggered')
|
||||
this.refreshData().finally(() => {
|
||||
uni.stopPullDownRefresh()
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic Control
|
||||
|
||||
```javascript
|
||||
// Start pull refresh
|
||||
uni.startPullDownRefresh()
|
||||
|
||||
// Stop pull refresh
|
||||
uni.stopPullDownRefresh()
|
||||
```
|
||||
|
||||
## Navigation Bar Loading
|
||||
|
||||
```javascript
|
||||
// Show loading in nav bar
|
||||
uni.showNavigationBarLoading()
|
||||
|
||||
// Hide loading
|
||||
uni.hideNavigationBarLoading()
|
||||
```
|
||||
|
||||
## Tab Bar Operations
|
||||
|
||||
### Show/Hide Tab Bar
|
||||
|
||||
```javascript
|
||||
// Hide tab bar
|
||||
uni.hideTabBar({
|
||||
animation: true
|
||||
})
|
||||
|
||||
// Show tab bar
|
||||
uni.showTabBar({
|
||||
animation: true
|
||||
})
|
||||
```
|
||||
|
||||
### Set Tab Bar Style
|
||||
|
||||
```javascript
|
||||
uni.setTabBarStyle({
|
||||
color: '#999',
|
||||
selectedColor: '#007AFF',
|
||||
backgroundColor: '#fff',
|
||||
borderStyle: 'black'
|
||||
})
|
||||
```
|
||||
|
||||
### Set Tab Bar Item
|
||||
|
||||
```javascript
|
||||
uni.setTabBarItem({
|
||||
index: 0,
|
||||
text: 'Home',
|
||||
iconPath: '/static/home.png',
|
||||
selectedIconPath: '/static/home-active.png'
|
||||
})
|
||||
```
|
||||
|
||||
### Add/Remove Tab Bar Badge
|
||||
|
||||
```javascript
|
||||
// Show badge
|
||||
uni.showTabBarRedDot({
|
||||
index: 2 // Tab index
|
||||
})
|
||||
|
||||
// Hide badge
|
||||
uni.hideTabBarRedDot({
|
||||
index: 2
|
||||
})
|
||||
|
||||
// Set badge text
|
||||
uni.setTabBarBadge({
|
||||
index: 2,
|
||||
text: '5'
|
||||
})
|
||||
|
||||
// Remove badge text
|
||||
uni.removeTabBarBadge({
|
||||
index: 2
|
||||
})
|
||||
```
|
||||
|
||||
## Preview Image
|
||||
|
||||
```javascript
|
||||
uni.previewImage({
|
||||
current: 'https://example.com/1.jpg', // Current image
|
||||
urls: [
|
||||
'https://example.com/1.jpg',
|
||||
'https://example.com/2.jpg',
|
||||
'https://example.com/3.jpg'
|
||||
],
|
||||
indicator: 'default', // default/number/none
|
||||
loop: false,
|
||||
longPressActions: {
|
||||
itemList: ['Save Image', 'Share'],
|
||||
success: (data) => {
|
||||
console.log('Long press:', data.tapIndex)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Save Image to Photos
|
||||
|
||||
```javascript
|
||||
uni.saveImageToPhotosAlbum({
|
||||
filePath: 'temp://path/to/image.jpg',
|
||||
success: () => {
|
||||
uni.showToast({ title: 'Saved' })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Toast Helper
|
||||
|
||||
```javascript
|
||||
const toast = {
|
||||
success(message, duration = 2000) {
|
||||
uni.showToast({ title: message, icon: 'success', duration })
|
||||
},
|
||||
error(message, duration = 2000) {
|
||||
uni.showToast({ title: message, icon: 'error', duration })
|
||||
},
|
||||
loading(message = 'Loading...') {
|
||||
uni.showLoading({ title: message, mask: true })
|
||||
},
|
||||
hide() {
|
||||
uni.hideLoading()
|
||||
uni.hideToast()
|
||||
},
|
||||
text(message, duration = 2000) {
|
||||
uni.showToast({ title: message, icon: 'none', duration })
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
toast.loading()
|
||||
fetchData()
|
||||
.then(() => toast.success('Loaded'))
|
||||
.catch(() => toast.error('Failed'))
|
||||
.finally(() => toast.hide())
|
||||
```
|
||||
|
||||
### Modal Helper
|
||||
|
||||
```javascript
|
||||
const modal = {
|
||||
confirm(title, content) {
|
||||
return new Promise((resolve) => {
|
||||
uni.showModal({
|
||||
title,
|
||||
content,
|
||||
success: (res) => resolve(res.confirm)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
alert(title, content) {
|
||||
return new Promise((resolve) => {
|
||||
uni.showModal({
|
||||
title,
|
||||
content,
|
||||
showCancel: false,
|
||||
success: () => resolve()
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
action(items) {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.showActionSheet({
|
||||
itemList: items,
|
||||
success: (res) => resolve(res.tapIndex),
|
||||
fail: reject
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
async function deleteItem(id) {
|
||||
const confirmed = await modal.confirm('Delete', 'Are you sure?')
|
||||
if (confirmed) {
|
||||
await api.delete(id)
|
||||
toast.success('Deleted')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/ui/prompt.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/ui/navigationbar.md
|
||||
- https://gitcode.com/dcloud/unidocs-zh/blob/main/docs/api/ui/tabbar.md
|
||||
-->
|
||||
5
.claude/skills/uni-helper/GENERATION.md
Normal file
5
.claude/skills/uni-helper/GENERATION.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Generation Info
|
||||
|
||||
- **Source:** `sources/uni-helper`
|
||||
- **Git SHA:** `286d8656dc077a7d9d6a50e647284ff1ea48ac6b`
|
||||
- **Generated:** 2026-01-30
|
||||
88
.claude/skills/uni-helper/SKILL.md
Normal file
88
.claude/skills/uni-helper/SKILL.md
Normal file
@@ -0,0 +1,88 @@
|
||||
---
|
||||
name: uni-helper
|
||||
description: Comprehensive skill reference for uni-helper ecosystem - AI-powered development tools for uni-app
|
||||
metadata:
|
||||
author: FlippeDround
|
||||
version: "2026.1.30"
|
||||
source: Generated from https://github.com/uni-helper/website, skills located at https://github.com/uni-helper/ai-tools
|
||||
---
|
||||
|
||||
> The skill is based on uni-helper documentation, generated at 2026-01-30.
|
||||
|
||||
uni-helper is an ecosystem of AI-powered development tools for uni-app, providing Vite plugins, utility libraries, TypeScript support, and development tools to enhance the uni-app development experience.
|
||||
|
||||
## Vite Plugins
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| vite-plugin-uni-pages | File-based routing system for uni-app with auto page discovery | [plugin-pages](references/plugin-pages.md) |
|
||||
| vite-plugin-uni-layouts | Nuxt-like layouts system for uni-app | [plugin-layouts](references/plugin-layouts.md) |
|
||||
| vite-plugin-uni-components | On-demand automatic component imports | [plugin-components](references/plugin-components.md) |
|
||||
| vite-plugin-uni-manifest | Write manifest.json in TypeScript | [plugin-manifest](references/plugin-manifest.md) |
|
||||
| vite-plugin-uni-platform | File-based platform compilation (*.h5|mp-weixin|app.*) | [plugin-platform](references/plugin-platform.md) |
|
||||
| vite-plugin-uni-platform-modifier | Platform modifiers for attributes/directives | [plugin-platform-modifier](references/plugin-platform-modifier.md) |
|
||||
| vite-plugin-uni-middleware | Middleware support for uni-app routing | [plugin-middleware](references/plugin-middleware.md) |
|
||||
|
||||
## Libraries
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| uni-use | VueUse-style composable utilities for uni-app | [lib-uni-use](references/lib-uni-use.md) |
|
||||
| uni-network | Promise-based HTTP client for uni-app | [lib-uni-network](references/lib-uni-network.md) |
|
||||
| uni-promises | Promise wrappers for uni-app APIs | [lib-uni-promises](references/lib-uni-promises.md) |
|
||||
| uni-typed | TypeScript type definitions for uni-app templates | [lib-uni-typed](references/lib-uni-typed.md) |
|
||||
|
||||
## Utilities
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| uni-env | Environment detection utilities for uni-app | [util-uni-env](references/util-uni-env.md) |
|
||||
| unocss-preset-uni | UnoCSS preset for uni-app | [util-unocss-preset](references/util-unocss-preset.md) |
|
||||
|
||||
## Project Starters
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| create-uni | CLI scaffolding tool for uni-app projects | [starter-create-uni](references/starter-create-uni.md) |
|
||||
| vitesse-uni-app | Vite-powered uni-app starter template | [starter-vitesse](references/starter-vitesse.md) |
|
||||
|
||||
## Plugin Order Best Practices
|
||||
|
||||
When using multiple uni-helper Vite plugins, the recommended order is:
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UniComponents(), // 1. Component auto-import
|
||||
UniPages(), // 2. File-based routing
|
||||
UniLayouts(), // 3. Layout system
|
||||
UniManifest(), // 4. Manifest generation
|
||||
UniPlatform(), // 5. Platform-specific files
|
||||
UniPlatformModifier(), // 6. Platform modifiers
|
||||
UniMiddleware(), // 7. Route middleware
|
||||
Uni(), // 8. Official uni-app plugin (always last)
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
Create a new uni-app project with create-uni:
|
||||
|
||||
```bash
|
||||
# npm 7+, extra double-dash is needed
|
||||
npm create uni@latest
|
||||
|
||||
# pnpm
|
||||
pnpm create uni
|
||||
|
||||
# yarn
|
||||
yarn create uni
|
||||
```
|
||||
|
||||
## Official Resources
|
||||
|
||||
- Website: https://uni-helper.js.org
|
||||
- GitHub: https://github.com/uni-helper
|
||||
- NPM Scope: @uni-helper
|
||||
221
.claude/skills/uni-helper/references/lib-uni-network.md
Normal file
221
.claude/skills/uni-helper/references/lib-uni-network.md
Normal file
@@ -0,0 +1,221 @@
|
||||
---
|
||||
name: uni-network
|
||||
description: Promise-based HTTP client for uni-app - axios-inspired API with uni.request as default transport
|
||||
---
|
||||
|
||||
# uni-network
|
||||
|
||||
Promise-based HTTP client for uni-app, inspired by axios@0.27.2. Uses uni.request/uni.uploadFile/uni.downloadFile as the underlying transport.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i @uni-helper/uni-network
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- Promise-based API
|
||||
- Request/response interceptors
|
||||
- Request cancellation
|
||||
- TypeScript support
|
||||
- Composition API integration
|
||||
- Upload/download support
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```ts
|
||||
import { un } from '@uni-helper/uni-network'
|
||||
|
||||
// GET request
|
||||
un('/user/123')
|
||||
|
||||
// POST request
|
||||
un({
|
||||
method: 'POST',
|
||||
url: '/user/123',
|
||||
data: {
|
||||
firstName: 'Fred',
|
||||
lastName: 'Flintstone',
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Request Aliases
|
||||
|
||||
```ts
|
||||
import { un } from '@uni-helper/uni-network'
|
||||
|
||||
// HTTP verbs
|
||||
un.get('/users')
|
||||
un.post('/users', { name: 'John' })
|
||||
un.put('/users/1', { name: 'Jane' })
|
||||
un.patch('/users/1', { age: 30 })
|
||||
un.delete('/users/1')
|
||||
|
||||
// Upload/download
|
||||
un.upload({
|
||||
url: '/upload',
|
||||
filePath: tempFilePath,
|
||||
name: 'file',
|
||||
})
|
||||
|
||||
un.download({
|
||||
url: '/files/report.pdf',
|
||||
})
|
||||
```
|
||||
|
||||
## Creating an Instance
|
||||
|
||||
```ts
|
||||
import { createUniNetwork } from '@uni-helper/uni-network'
|
||||
|
||||
const http = createUniNetwork({
|
||||
baseURL: 'https://api.example.com',
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
// Use the instance
|
||||
http.get('/users')
|
||||
```
|
||||
|
||||
## Interceptors
|
||||
|
||||
```ts
|
||||
import { un } from '@uni-helper/uni-network'
|
||||
|
||||
// Request interceptor
|
||||
un.interceptors.request.use(
|
||||
(config) => {
|
||||
// Add auth token
|
||||
const token = uni.getStorageSync('token')
|
||||
if (token) {
|
||||
config.headers = config.headers || {}
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// Response interceptor
|
||||
un.interceptors.response.use(
|
||||
(response) => {
|
||||
// Transform response data
|
||||
return response.data
|
||||
},
|
||||
(error) => {
|
||||
// Handle errors globally
|
||||
if (error.statusCode === 401) {
|
||||
uni.redirectTo({ url: '/pages/login/index' })
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
```ts
|
||||
interface UniNetworkConfig {
|
||||
// URL
|
||||
url?: string
|
||||
// Base URL
|
||||
baseURL?: string
|
||||
// Method
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | ...
|
||||
// Headers
|
||||
headers?: Record<string, string>
|
||||
// Request data
|
||||
data?: any
|
||||
// Query params
|
||||
params?: Record<string, any>
|
||||
// Timeout in ms
|
||||
timeout?: number
|
||||
// Response type
|
||||
responseType?: 'text' | 'arraybuffer'
|
||||
// Data type
|
||||
dataType?: 'json' | 'string'
|
||||
// Enable http2
|
||||
enableHttp2?: boolean
|
||||
// Enable quic
|
||||
enableQuic?: boolean
|
||||
// Enable cache
|
||||
enableCache?: boolean
|
||||
// SSL verify
|
||||
sslVerify?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
## Request Cancellation
|
||||
|
||||
```ts
|
||||
import { un } from '@uni-helper/uni-network'
|
||||
|
||||
const controller = new AbortController()
|
||||
|
||||
un.get('/long-request', {
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
// Cancel after 5 seconds
|
||||
setTimeout(() => {
|
||||
controller.abort()
|
||||
}, 5000)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```ts
|
||||
import { un, UniNetworkError } from '@uni-helper/uni-network'
|
||||
|
||||
try {
|
||||
const response = await un.get('/users')
|
||||
} catch (error) {
|
||||
if (error instanceof UniNetworkError) {
|
||||
console.log('Request failed:', error.message)
|
||||
console.log('Status:', error.statusCode)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Composition API
|
||||
|
||||
```ts
|
||||
import { useUniNetwork } from '@uni-helper/uni-network'
|
||||
|
||||
const { data, error, loading, execute } = useUniNetwork({
|
||||
url: '/users',
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
// Execute manually
|
||||
await execute()
|
||||
```
|
||||
|
||||
## TypeScript Support
|
||||
|
||||
```ts
|
||||
import { un } from '@uni-helper/uni-network'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
// Typed response
|
||||
const { data } = await un.get<User>('/users/1')
|
||||
console.log(data.name) // Type-safe access
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/uni-network
|
||||
- https://uni-helper.js.org/uni-network
|
||||
-->
|
||||
197
.claude/skills/uni-helper/references/lib-uni-promises.md
Normal file
197
.claude/skills/uni-helper/references/lib-uni-promises.md
Normal file
@@ -0,0 +1,197 @@
|
||||
---
|
||||
name: uni-promises
|
||||
description: Promise wrappers for uni-app APIs - convert callback-based APIs to Promise-based
|
||||
---
|
||||
|
||||
# uni-promises
|
||||
|
||||
Promise wrappers for uni-app's callback-based APIs. Convert uni-app APIs to return Promises for better async/await support.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i @uni-helper/uni-promises
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Instead of using callbacks:
|
||||
|
||||
```ts
|
||||
// Original callback style
|
||||
uni.request({
|
||||
url: 'https://api.example.com',
|
||||
success: (res) => {
|
||||
console.log(res.data)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error(err)
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Use Promises:
|
||||
|
||||
```ts
|
||||
import { request } from '@uni-helper/uni-promises'
|
||||
|
||||
// Promise style
|
||||
const res = await request({
|
||||
url: 'https://api.example.com',
|
||||
})
|
||||
console.log(res.data)
|
||||
```
|
||||
|
||||
## Available APIs
|
||||
|
||||
Most uni-app APIs are wrapped:
|
||||
|
||||
### Network
|
||||
- `request` - HTTP request
|
||||
- `uploadFile` - File upload
|
||||
- `downloadFile` - File download
|
||||
- `connectSocket` - WebSocket
|
||||
|
||||
### Storage
|
||||
- `setStorage` - Set storage
|
||||
- `getStorage` - Get storage
|
||||
- `removeStorage` - Remove storage
|
||||
- `clearStorage` - Clear all storage
|
||||
- `getStorageInfo` - Storage info
|
||||
|
||||
### Media
|
||||
- `chooseImage` - Select images
|
||||
- `chooseVideo` - Select video
|
||||
- `chooseMedia` - Select media
|
||||
- `previewImage` - Preview images
|
||||
- `saveImageToPhotosAlbum` - Save image
|
||||
- `compressImage` - Compress image
|
||||
|
||||
### File
|
||||
- `saveFile` - Save file
|
||||
- `getFileInfo` - File info
|
||||
- `getSavedFileList` - Saved files list
|
||||
- `removeSavedFile` - Remove saved file
|
||||
- `openDocument` - Open document
|
||||
|
||||
### Location
|
||||
- `getLocation` - Get location
|
||||
- `chooseLocation` - Choose location
|
||||
- `openLocation` - Open location
|
||||
|
||||
### Device
|
||||
- `getSystemInfo` - System info
|
||||
- `getNetworkType` - Network type
|
||||
- `scanCode` - QR/barcode scan
|
||||
- `setClipboardData` - Copy to clipboard
|
||||
- `getClipboardData` - Get clipboard
|
||||
|
||||
### UI
|
||||
- `showToast` - Show toast
|
||||
- `showModal` - Show modal
|
||||
- `showActionSheet` - Show action sheet
|
||||
- `showLoading` - Show loading
|
||||
- `hideLoading` - Hide loading
|
||||
- `showNavigationBarLoading` - Nav loading
|
||||
- `hideNavigationBarLoading` - Hide nav loading
|
||||
- `setNavigationBarTitle` - Set nav title
|
||||
- `setNavigationBarColor` - Set nav color
|
||||
- `pageScrollTo` - Scroll to position
|
||||
|
||||
### Navigation
|
||||
- `navigateTo` - Navigate to page
|
||||
- `redirectTo` - Redirect to page
|
||||
- `reLaunch` - Re-launch app
|
||||
- `switchTab` - Switch tab
|
||||
- `navigateBack` - Go back
|
||||
|
||||
### Login
|
||||
- `login` - User login
|
||||
- `checkSession` - Check session
|
||||
- `getUserProfile` - Get user profile
|
||||
- `getUserInfo` - Get user info
|
||||
|
||||
### Payment
|
||||
- `requestPayment` - Request payment
|
||||
|
||||
## Example Usage
|
||||
|
||||
```ts
|
||||
import {
|
||||
showModal,
|
||||
showToast,
|
||||
getStorage,
|
||||
navigateTo,
|
||||
getSystemInfo,
|
||||
chooseImage,
|
||||
uploadFile,
|
||||
} from '@uni-helper/uni-promises'
|
||||
|
||||
async function handleUserAction() {
|
||||
// Show confirmation
|
||||
const { confirm } = await showModal({
|
||||
title: 'Confirm',
|
||||
content: 'Are you sure?',
|
||||
})
|
||||
|
||||
if (!confirm) return
|
||||
|
||||
try {
|
||||
// Get cached data
|
||||
const { data: token } = await getStorage({ key: 'token' })
|
||||
|
||||
// Get system info
|
||||
const systemInfo = await getSystemInfo()
|
||||
console.log('Platform:', systemInfo.platform)
|
||||
|
||||
// Select image
|
||||
const { tempFilePaths } = await chooseImage({
|
||||
count: 1,
|
||||
sizeType: ['compressed'],
|
||||
})
|
||||
|
||||
// Upload file
|
||||
const uploadRes = await uploadFile({
|
||||
url: 'https://api.example.com/upload',
|
||||
filePath: tempFilePaths[0],
|
||||
name: 'file',
|
||||
})
|
||||
|
||||
await showToast({
|
||||
title: 'Success!',
|
||||
icon: 'success',
|
||||
})
|
||||
|
||||
// Navigate
|
||||
await navigateTo({
|
||||
url: '/pages/success/index',
|
||||
})
|
||||
} catch (error) {
|
||||
await showToast({
|
||||
title: error.message || 'Failed',
|
||||
icon: 'error',
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All wrapped APIs reject with standard Error objects:
|
||||
|
||||
```ts
|
||||
import { request } from '@uni-helper/uni-promises'
|
||||
|
||||
try {
|
||||
const res = await request({ url: 'https://api.example.com' })
|
||||
} catch (error) {
|
||||
// error.message contains the fail callback message
|
||||
console.error('Request failed:', error.message)
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/uni-promises
|
||||
- https://uni-helper.js.org/uni-promises
|
||||
-->
|
||||
200
.claude/skills/uni-helper/references/lib-uni-typed.md
Normal file
200
.claude/skills/uni-helper/references/lib-uni-typed.md
Normal file
@@ -0,0 +1,200 @@
|
||||
---
|
||||
name: uni-typed
|
||||
description: TypeScript type definitions for uni-app templates - complete type safety for uni-app components
|
||||
---
|
||||
|
||||
# uni-typed
|
||||
|
||||
TypeScript type definitions for uni-app template sections. Provides complete type safety and IntelliSense for uni-app components.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# For uni-app
|
||||
npm i -D @uni-helper/uni-app-types
|
||||
|
||||
# For uni-ui
|
||||
npm i -D @uni-helper/uni-ui-types
|
||||
|
||||
# For uni-cloud
|
||||
npm i -D @uni-helper/uni-cloud-types
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
### Uni-app Types
|
||||
|
||||
```json
|
||||
// tsconfig.json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"types": ["@uni-helper/uni-app-types"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Uni-ui Types
|
||||
|
||||
```json
|
||||
// tsconfig.json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"@uni-helper/uni-app-types",
|
||||
"@uni-helper/uni-ui-types"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- Type-safe template event handlers
|
||||
- Component prop type checking
|
||||
- Custom event type definitions
|
||||
- Ref type inference for components
|
||||
|
||||
## Component Types
|
||||
|
||||
### Template Type Safety
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
const inputValue = ref('')
|
||||
const count = ref(0)
|
||||
|
||||
const handleInput = (e: UniHelper.InputOnInputEvent) => {
|
||||
inputValue.value = e.detail.value
|
||||
}
|
||||
|
||||
const handleChange = (e: UniHelper.SwitchOnChangeEvent) => {
|
||||
console.log(e.detail.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Type-safe component usage -->
|
||||
<input
|
||||
type="text"
|
||||
:value="inputValue"
|
||||
@input="handleInput"
|
||||
/>
|
||||
|
||||
<switch :checked="true" @change="handleChange" />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Component Ref Types
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
// Type-safe component refs
|
||||
const videoRef = ref<UniHelper.VideoInstance>()
|
||||
const mapRef = ref<UniHelper.MapInstance>()
|
||||
|
||||
onMounted(() => {
|
||||
// IntelliSense for component methods
|
||||
videoRef.value?.play()
|
||||
videoRef.value?.pause()
|
||||
videoRef.value?.seek(100)
|
||||
|
||||
mapRef.value?.moveToLocation({
|
||||
latitude: 39.9,
|
||||
longitude: 116.4,
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<video ref="videoRef" src="..." />
|
||||
<map ref="mapRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Event Types
|
||||
|
||||
### Common Event Types
|
||||
|
||||
```ts
|
||||
// Input events
|
||||
UniHelper.InputOnInputEvent
|
||||
UniHelper.InputOnBlurEvent
|
||||
UniHelper.InputOnFocusEvent
|
||||
|
||||
// Form events
|
||||
UniHelper.SwitchOnChangeEvent
|
||||
UniHelper.CheckboxOnChangeEvent
|
||||
UniHelper.RadioOnChangeEvent
|
||||
UniHelper.PickerOnChangeEvent
|
||||
UniHelper.SliderOnChangeEvent
|
||||
|
||||
// Media events
|
||||
UniHelper.VideoOnPlayEvent
|
||||
UniHelper.VideoOnPauseEvent
|
||||
UniHelper.VideoOnEndedEvent
|
||||
UniHelper.VideoOnTimeUpdateEvent
|
||||
|
||||
// Touch events
|
||||
UniHelper.ViewOnTouchstartEvent
|
||||
UniHelper.ViewOnTouchmoveEvent
|
||||
UniHelper.ViewOnTouchendEvent
|
||||
UniHelper.ViewOnTapEvent
|
||||
UniHelper.ViewOnLongpressEvent
|
||||
|
||||
// Scroll events
|
||||
UniHelper.ScrollViewOnScrollEvent
|
||||
UniHelper.ScrollViewOnScrolltolowerEvent
|
||||
UniHelper.ScrollViewOnScrolltoupperEvent
|
||||
```
|
||||
|
||||
### Custom Events
|
||||
|
||||
Define custom event types for your components:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// Child component
|
||||
const emit = defineEmits<{
|
||||
change: [value: string]
|
||||
submit: [data: { id: number; name: string }]
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// Parent component
|
||||
import type { MyComponentOnChangeEvent } from './types'
|
||||
|
||||
const handleChange = (e: MyComponentOnChangeEvent) => {
|
||||
console.log(e.detail.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<my-component @change="handleChange" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Why uni-typed?
|
||||
|
||||
DCloud's `@dcloudio/types` only provides TypeScript support for script sections. uni-typed fills the gap for template section type safety, providing:
|
||||
|
||||
- Component prop validation
|
||||
- Event handler type checking
|
||||
- Method IntelliSense on component refs
|
||||
- Better IDE support (VS Code, WebStorm)
|
||||
|
||||
## Migration from v0 to v1
|
||||
|
||||
See the [migration guide](https://uni-helper.js.org/uni-typed/other/migrate-v0-to-v1) for upgrading instructions.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/uni-typed
|
||||
- https://uni-helper.js.org/uni-typed
|
||||
-->
|
||||
185
.claude/skills/uni-helper/references/lib-uni-use.md
Normal file
185
.claude/skills/uni-helper/references/lib-uni-use.md
Normal file
@@ -0,0 +1,185 @@
|
||||
---
|
||||
name: uni-use
|
||||
description: VueUse-style composable utilities for uni-app development
|
||||
---
|
||||
|
||||
# uni-use
|
||||
|
||||
VueUse-style composable utilities specifically designed for uni-app. Provides reactive wrappers around uni-app APIs.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i @uni-helper/uni-use @vueuse/core@9
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { tryOnLoad, useClipboard, useSystemInfo } from '@uni-helper/uni-use'
|
||||
|
||||
tryOnLoad(() => {
|
||||
console.log('Page loaded')
|
||||
})
|
||||
|
||||
const { copy, text } = useClipboard()
|
||||
const { systemInfo } = useSystemInfo()
|
||||
```
|
||||
|
||||
## Auto Import Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import { uniuseAutoImports } from '@uni-helper/uni-use'
|
||||
import autoImport from 'unplugin-auto-import/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
autoImport({
|
||||
imports: [uniuseAutoImports()],
|
||||
}),
|
||||
uni(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Available Composables
|
||||
|
||||
### Lifecycle
|
||||
|
||||
| Composable | Description |
|
||||
|------------|-------------|
|
||||
| `tryOnLoad` | onLoad with try-catch |
|
||||
| `tryOnShow` | onShow with try-catch |
|
||||
| `tryOnHide` | onHide with try-catch |
|
||||
| `tryOnReady` | onReady with try-catch |
|
||||
| `tryOnUnload` | onUnload with try-catch |
|
||||
| `tryOnPullDownRefresh` | onPullDownRefresh with try-catch |
|
||||
| `tryOnReachBottom` | onReachBottom with try-catch |
|
||||
| `tryOnPageScroll` | onPageScroll with try-catch |
|
||||
| `tryOnTabItemTap` | onTabItemTap with try-catch |
|
||||
|
||||
### System
|
||||
|
||||
| Composable | Description |
|
||||
|------------|-------------|
|
||||
| `useSystemInfo` | Reactive system information |
|
||||
| `useDeviceInfo` | Device information |
|
||||
| `useWindowInfo` | Window dimensions |
|
||||
| `useAppTheme` | App theme (dark/light) |
|
||||
| `useNetworkStatus` | Network connection status |
|
||||
| `useBattery` | Battery status |
|
||||
|
||||
### Storage
|
||||
|
||||
| Composable | Description |
|
||||
|------------|-------------|
|
||||
| `useStorage` | Reactive local storage |
|
||||
| `useStorageAsync` | Async storage operations |
|
||||
|
||||
### UI
|
||||
|
||||
| Composable | Description |
|
||||
|------------|-------------|
|
||||
| `useClipboard` | Clipboard operations |
|
||||
| `useToast` | Toast notifications |
|
||||
| `useModal` | Modal dialogs |
|
||||
| `useActionSheet` | Action sheet |
|
||||
| `useLoading` | Loading indicator |
|
||||
| `useNavigationBar` | Navigation bar control |
|
||||
| `usePullDownRefresh` | Pull-to-refresh |
|
||||
|
||||
### Location
|
||||
|
||||
| Composable | Description |
|
||||
|------------|-------------|
|
||||
| `useLocation` | Current location |
|
||||
| `useChooseLocation` | Location picker |
|
||||
|
||||
### Media
|
||||
|
||||
| Composable | Description |
|
||||
|------------|-------------|
|
||||
| `useImage` | Image operations |
|
||||
| `useCamera` | Camera access |
|
||||
| `useRecorder` | Audio recording |
|
||||
|
||||
## Example Usage
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useClipboard, useSystemInfo, useStorage, tryOnLoad } from '@uni-helper/uni-use'
|
||||
|
||||
// System info
|
||||
const { systemInfo, safeArea } = useSystemInfo()
|
||||
|
||||
// Clipboard
|
||||
const { text, copy, isSupported } = useClipboard()
|
||||
const handleCopy = async () => {
|
||||
await copy('Hello uni-app')
|
||||
uni.showToast({ title: 'Copied!' })
|
||||
}
|
||||
|
||||
// Storage
|
||||
const userToken = useStorage('token', '')
|
||||
const saveToken = (token: string) => {
|
||||
userToken.value = token
|
||||
}
|
||||
|
||||
// Lifecycle
|
||||
tryOnLoad((options) => {
|
||||
console.log('Page options:', options)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<view class="page">
|
||||
<text>Platform: {{ systemInfo.platform }}</text>
|
||||
<text>Safe area top: {{ safeArea?.top }}px</text>
|
||||
<button @click="handleCopy">Copy to clipboard</button>
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Build Configuration
|
||||
|
||||
For Vite + Vue3 projects targeting ES6:
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
export default defineConfig({
|
||||
build: {
|
||||
target: 'es6',
|
||||
cssTarget: 'chrome61',
|
||||
},
|
||||
optimizeDeps: {
|
||||
exclude: ['vue-demi'],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Add polyfills in `main.ts` if needed:
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
import 'core-js/actual/array/iterator'
|
||||
import 'core-js/actual/promise'
|
||||
import 'core-js/actual/object/assign'
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
- Mini Program and App environments lack some globals (window, navigator)
|
||||
- Cannot use top-level await
|
||||
- Some VueUse features may not work in uni-app
|
||||
|
||||
## See Also
|
||||
|
||||
- Full API docs: https://uni-helper.js.org/uni-use/apis
|
||||
- VueUse: https://vueuse.org/
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/uni-use
|
||||
- https://uni-helper.js.org/uni-use
|
||||
-->
|
||||
93
.claude/skills/uni-helper/references/plugin-components.md
Normal file
93
.claude/skills/uni-helper/references/plugin-components.md
Normal file
@@ -0,0 +1,93 @@
|
||||
---
|
||||
name: vite-plugin-uni-components
|
||||
description: On-demand automatic component imports for uni-app - derived from unplugin-vue-components
|
||||
---
|
||||
|
||||
# vite-plugin-uni-components
|
||||
|
||||
Automatic on-demand component imports for uni-app. Derived from unplugin-vue-components with uni-app specific adaptations.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-components
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import Components from '@uni-helper/vite-plugin-uni-components'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
Components(), // Must be before Uni()
|
||||
Uni(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- Automatic component imports from `src/components`
|
||||
- Supports UI library resolvers
|
||||
- Generates TypeScript declarations
|
||||
- Handles `default` export for third-party UI libraries
|
||||
|
||||
## Supported UI Libraries
|
||||
|
||||
Built-in resolvers for:
|
||||
|
||||
| Library | Import |
|
||||
|---------|--------|
|
||||
| Ano UI | `AnoUIResolver()` |
|
||||
| uni-ui | `UniUIResolver()` |
|
||||
| wot-design-uni | `WotDesignUniResolver()` |
|
||||
| uv-uni | `UvUniResolver()` |
|
||||
| uview-pro | `UviewProResolver()` |
|
||||
| z-paging | `ZPagingResolver()` |
|
||||
|
||||
## TypeScript Declarations
|
||||
|
||||
For pnpm users, create `.npmrc`:
|
||||
|
||||
```ini
|
||||
shamefully-hoist = true
|
||||
```
|
||||
|
||||
Generated `components.d.ts` example:
|
||||
|
||||
```ts
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
AButton: typeof import('ano-ui/components/AButton/AButton.vue')['default']
|
||||
UniCalendar: typeof import('@dcloudio/uni-ui/lib/uni-calendar/uni-calendar.vue')['default']
|
||||
MyComponent: typeof import('./src/components/MyComponent.vue')['default']
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Third-Party Component Handling
|
||||
|
||||
For third-party components like `@dcloudio/uni-ui` and `ano-ui`, the plugin automatically adds the `default` property to handle H5 compatibility issues:
|
||||
|
||||
```diff
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
- AButton: typeof import('ano-ui/components/AButton/AButton.vue')['AButton']
|
||||
+ AButton: typeof import('ano-ui/components/AButton/AButton.vue')['default']
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Full Configuration
|
||||
|
||||
See [unplugin-vue-components documentation](https://github.com/antfu/unplugin-vue-components) for all options.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-components
|
||||
- https://uni-helper.js.org/vite-plugin-uni-components
|
||||
-->
|
||||
143
.claude/skills/uni-helper/references/plugin-layouts.md
Normal file
143
.claude/skills/uni-helper/references/plugin-layouts.md
Normal file
@@ -0,0 +1,143 @@
|
||||
---
|
||||
name: vite-plugin-uni-layouts
|
||||
description: Nuxt-like layouts system for Vite-powered uni-app projects
|
||||
---
|
||||
|
||||
# vite-plugin-uni-layouts
|
||||
|
||||
Provides a Nuxt-like layout system for uni-app. Wraps pages with reusable layout components.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-layouts
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import uni from '@dcloudio/vite-plugin-uni'
|
||||
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [UniLayouts(), uni()],
|
||||
})
|
||||
```
|
||||
|
||||
## Creating Layouts
|
||||
|
||||
Create layout files in `src/layouts/` directory:
|
||||
|
||||
```vue
|
||||
<!-- src/layouts/default.vue -->
|
||||
<template>
|
||||
<view class="layout">
|
||||
<slot name="header" />
|
||||
<slot>main content</slot>
|
||||
<slot name="footer" />
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Applying Layouts
|
||||
|
||||
### Via pages.json (traditional)
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [{
|
||||
"path": "pages/index/index",
|
||||
"layout": "default"
|
||||
},
|
||||
{
|
||||
"path": "pages/about/index",
|
||||
"layout": false // Disable layout
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
### Via definePage (recommended)
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
definePage({
|
||||
layout: 'default',
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Dynamic Layouts
|
||||
|
||||
Use the `<uni-layout>` component for dynamic layout switching:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const layoutName = ref('default')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Disable page layout first -->
|
||||
<uni-layout :name="layoutName">
|
||||
<template #header>
|
||||
<text>Header content</text>
|
||||
</template>
|
||||
|
||||
Main content here
|
||||
|
||||
<template #footer>
|
||||
<text>Footer content</text>
|
||||
</template>
|
||||
</uni-layout>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Accessing Layout Ref
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const uniLayout = ref()
|
||||
|
||||
onMounted(() => {
|
||||
console.log(uniLayout.value) // Access layout component
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<uni-layout ref="uniLayout">
|
||||
Content
|
||||
</uni-layout>
|
||||
</template>
|
||||
```
|
||||
|
||||
Options API:
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
onLoad() {
|
||||
console.log(this.$refs.uniLayout)
|
||||
},
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
The plugin does two things:
|
||||
|
||||
1. Auto-scans and globally registers components from `layouts/` directory
|
||||
2. Wraps pages with the specified layout component
|
||||
|
||||
> **Note:** WeChat Mini Program limitation - If using `web-view` component, layout wrapping may not work properly.
|
||||
|
||||
## Configuration
|
||||
|
||||
See [type definitions](https://github.com/uni-helper/vite-plugin-uni-layouts/blob/main/src/types.ts) for all options.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-layouts
|
||||
- https://uni-helper.js.org/vite-plugin-uni-layouts
|
||||
-->
|
||||
103
.claude/skills/uni-helper/references/plugin-manifest.md
Normal file
103
.claude/skills/uni-helper/references/plugin-manifest.md
Normal file
@@ -0,0 +1,103 @@
|
||||
---
|
||||
name: vite-plugin-uni-manifest
|
||||
description: Write uni-app manifest.json in TypeScript with type safety and IntelliSense
|
||||
---
|
||||
|
||||
# vite-plugin-uni-manifest
|
||||
|
||||
Write your uni-app `manifest.json` configuration in TypeScript with full type safety and IntelliSense support.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-manifest
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [UniManifest(), Uni()],
|
||||
})
|
||||
```
|
||||
|
||||
## Configuration File
|
||||
|
||||
Create `manifest.config.ts` (or .js/.json):
|
||||
|
||||
```ts
|
||||
// manifest.config.ts
|
||||
import { defineManifestConfig } from '@uni-helper/vite-plugin-uni-manifest'
|
||||
|
||||
export default defineManifestConfig({
|
||||
name: 'my-uni-app',
|
||||
appid: '__UNI__XXXXXXX',
|
||||
description: 'My awesome uni-app project',
|
||||
versionName: '1.0.0',
|
||||
versionCode: '100',
|
||||
transformPx: false,
|
||||
app: {
|
||||
// App-specific config
|
||||
},
|
||||
mp-weixin: {
|
||||
// WeChat Mini Program config
|
||||
},
|
||||
mp-alipay: {
|
||||
// Alipay Mini Program config
|
||||
},
|
||||
h5: {
|
||||
// H5 config
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
- **Type Safety**: Full TypeScript intellisense for all manifest properties
|
||||
- **Code Reuse**: Import and reuse configuration values
|
||||
- **Comments**: Add comments to explain configuration choices
|
||||
- **Environment-based Config**: Use conditionals for different environments
|
||||
|
||||
## Example with Dynamic Config
|
||||
|
||||
```ts
|
||||
import { defineManifestConfig } from '@uni-helper/vite-plugin-uni-manifest'
|
||||
import { version } from './package.json'
|
||||
|
||||
export default defineManifestConfig({
|
||||
name: 'My App',
|
||||
versionName: version,
|
||||
versionCode: version.replace(/\./g, ''),
|
||||
|
||||
// Platform-specific config
|
||||
'mp-weixin': {
|
||||
appid: process.env.WX_APPID || '',
|
||||
setting: {
|
||||
es6: true,
|
||||
enhance: true,
|
||||
},
|
||||
},
|
||||
|
||||
h5: {
|
||||
title: 'My H5 App',
|
||||
router: {
|
||||
mode: 'hash',
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
See [types.ts](https://github.com/uni-helper/vite-plugin-uni-manifest/tree/main/packages/core/src/types.ts) for all available options.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-manifest
|
||||
- https://uni-helper.js.org/vite-plugin-uni-manifest
|
||||
-->
|
||||
181
.claude/skills/uni-helper/references/plugin-middleware.md
Normal file
181
.claude/skills/uni-helper/references/plugin-middleware.md
Normal file
@@ -0,0 +1,181 @@
|
||||
---
|
||||
name: vite-plugin-uni-middleware
|
||||
description: Route middleware support for uni-app - implement guards, auth, and page lifecycle hooks
|
||||
---
|
||||
|
||||
# vite-plugin-uni-middleware
|
||||
|
||||
Add Express-style middleware support to uni-app routing. Implement authentication guards, page analytics, and custom route logic.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-middleware
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import UniMiddleware from '@uni-helper/vite-plugin-uni-middleware'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [UniMiddleware(), Uni()],
|
||||
})
|
||||
```
|
||||
|
||||
## Creating Middleware
|
||||
|
||||
Create middleware files in `src/middleware/` directory:
|
||||
|
||||
```ts
|
||||
// src/middleware/auth.ts
|
||||
import { defineMiddleware } from '@uni-helper/vite-plugin-middleware'
|
||||
|
||||
export default defineMiddleware((to, from, next) => {
|
||||
const token = uni.getStorageSync('token')
|
||||
|
||||
if (!token && to.path !== '/pages/login/index') {
|
||||
// Redirect to login
|
||||
next('/pages/login/index')
|
||||
} else {
|
||||
// Continue navigation
|
||||
next()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
// src/middleware/analytics.ts
|
||||
export default defineMiddleware((to, from, next) => {
|
||||
// Track page view
|
||||
uni.report('page_view', {
|
||||
path: to.path,
|
||||
from: from.path,
|
||||
timestamp: Date.now(),
|
||||
})
|
||||
|
||||
next()
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
// src/middleware/logger.ts
|
||||
export default defineMiddleware((to, from, next) => {
|
||||
console.log(`[Router] ${from.path} -> ${to.path}`)
|
||||
next()
|
||||
})
|
||||
```
|
||||
|
||||
## Applying Middleware
|
||||
|
||||
### Via definePage (recommended)
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
definePage({
|
||||
middlewares: ['auth', 'analytics'],
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Via pages.json
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [{
|
||||
"path": "pages/profile/index",
|
||||
"middlewares": ["auth"]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
### Global Middleware
|
||||
|
||||
Create `src/middleware/index.ts` for global middleware:
|
||||
|
||||
```ts
|
||||
// src/middleware/index.ts
|
||||
export default defineMiddleware((to, from, next) => {
|
||||
// Runs on every navigation
|
||||
console.log('Global middleware')
|
||||
next()
|
||||
})
|
||||
```
|
||||
|
||||
## Middleware Context
|
||||
|
||||
```ts
|
||||
interface MiddlewareContext {
|
||||
to: {
|
||||
path: string
|
||||
query: Record<string, string>
|
||||
meta?: Record<string, any>
|
||||
}
|
||||
from: {
|
||||
path: string
|
||||
query: Record<string, string>
|
||||
}
|
||||
next: (path?: string) => void
|
||||
}
|
||||
```
|
||||
|
||||
## Middleware Order
|
||||
|
||||
Middleware executes in declaration order:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
definePage({
|
||||
// Runs: logger -> auth -> analytics
|
||||
middlewares: ['logger', 'auth', 'analytics'],
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Navigation Control
|
||||
|
||||
```ts
|
||||
export default defineMiddleware((to, from, next) => {
|
||||
// Continue to route
|
||||
next()
|
||||
|
||||
// Redirect to different route
|
||||
next('/pages/other/index')
|
||||
|
||||
// Redirect with query
|
||||
next({
|
||||
path: '/pages/login/index',
|
||||
query: { redirect: to.path },
|
||||
})
|
||||
|
||||
// Cancel navigation (stay on current page)
|
||||
next(false)
|
||||
})
|
||||
```
|
||||
|
||||
## Async Middleware
|
||||
|
||||
```ts
|
||||
export default defineMiddleware(async (to, from, next) => {
|
||||
try {
|
||||
const user = await fetchUserInfo()
|
||||
|
||||
if (user.isBanned) {
|
||||
next('/pages/banned/index')
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
} catch (error) {
|
||||
next('/pages/error/index')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-middleware
|
||||
- https://uni-helper.js.org/vite-plugin-uni-middleware
|
||||
-->
|
||||
186
.claude/skills/uni-helper/references/plugin-pages.md
Normal file
186
.claude/skills/uni-helper/references/plugin-pages.md
Normal file
@@ -0,0 +1,186 @@
|
||||
---
|
||||
name: vite-plugin-uni-pages
|
||||
description: File-based routing system for Vite-powered uni-app projects with automatic page discovery and TypeScript support
|
||||
---
|
||||
|
||||
# vite-plugin-uni-pages
|
||||
|
||||
Provides file-based routing for uni-app projects using Vite. Automatically generates `pages.json` configuration from your file structure.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-pages
|
||||
```
|
||||
|
||||
## Basic Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import UniPages from '@uni-helper/vite-plugin-uni-pages'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
// Place UniPages before Uni
|
||||
export default defineConfig({
|
||||
plugins: [UniPages(), Uni()],
|
||||
})
|
||||
```
|
||||
|
||||
## TypeScript Support
|
||||
|
||||
Add types to `tsconfig.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"types": ["@uni-helper/vite-plugin-uni-pages"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Global Configuration
|
||||
|
||||
Create `pages.config.ts` (or .js/.json) for global settings:
|
||||
|
||||
```ts
|
||||
// pages.config.ts
|
||||
import { defineUniPages } from '@uni-helper/vite-plugin-uni-pages'
|
||||
|
||||
export default defineUniPages({
|
||||
// Optional: manual pages have highest priority
|
||||
pages: [],
|
||||
globalStyle: {
|
||||
navigationBarTextStyle: 'black',
|
||||
navigationBarTitleText: '@uni-helper',
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Virtual Module
|
||||
|
||||
Access page metadata via virtual module:
|
||||
|
||||
```ts
|
||||
/// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
|
||||
import { pages } from 'virtual:uni-pages'
|
||||
|
||||
console.log(pages)
|
||||
```
|
||||
|
||||
## definePage Macro
|
||||
|
||||
Define page configuration directly in SFC files:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// Object form
|
||||
definePage({
|
||||
style: {
|
||||
navigationBarTitleText: 'hello world',
|
||||
},
|
||||
middlewares: ['auth'],
|
||||
})
|
||||
|
||||
// Function form (supports TypeScript, async)
|
||||
definePage(() => {
|
||||
return {
|
||||
style: {
|
||||
navigationBarTitleText: 'dynamic title',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
// Async form
|
||||
definePage(async () => {
|
||||
const title = await fetchTitle()
|
||||
return {
|
||||
style: { navigationBarTitleText: title },
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Important Notes for definePage
|
||||
|
||||
- Write inside `<script>` block
|
||||
- `definePage` runs in a different scope than SFC (no access to SFC variables)
|
||||
- Page path is auto-generated from file path
|
||||
- Only one `definePage` per file
|
||||
- Supports importing external libraries (pure JS only)
|
||||
- Supports TypeScript type imports (types are stripped)
|
||||
|
||||
### Using with Condition Compile
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
import { isH5 } from '@uni-helper/uni-env'
|
||||
|
||||
definePage(() => {
|
||||
const title = isH5 ? 'H5 Environment' : 'Other Platform'
|
||||
return {
|
||||
style: { navigationBarTitleText: title },
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
```ts
|
||||
export interface Options {
|
||||
/** Generate TypeScript declarations */
|
||||
dts?: boolean | string // default: true (outputs uni-pages.d.ts)
|
||||
|
||||
/** Config file pattern */
|
||||
configSource: string // default: 'pages.config.(ts|mts|cts|js|cjs|mjs|json)'
|
||||
|
||||
/** Default home page */
|
||||
homePage: string // default: 'pages/index' or 'pages/index/index'
|
||||
|
||||
/** Merge with existing pages.json */
|
||||
mergePages: boolean // default: true
|
||||
|
||||
/** Pages directory */
|
||||
dir: string // default: 'src/pages'
|
||||
|
||||
/** Sub-packages directories */
|
||||
subPackages: string[] // e.g., ['src/pages-sub']
|
||||
|
||||
/** Output directory for pages.json */
|
||||
outDir: string // default: 'src'
|
||||
|
||||
/** Exclude patterns */
|
||||
exclude: string[] // default: []
|
||||
|
||||
/** Route block language in SFC */
|
||||
routeBlockLang: 'json5' | 'jsonc' | 'json' | 'yaml' | 'yml' // default: 'json5'
|
||||
|
||||
// Lifecycle hooks
|
||||
onBeforeLoadUserConfig?: (ctx: PageContext) => void
|
||||
onAfterLoadUserConfig?: (ctx: PageContext) => void
|
||||
onBeforeScanPages?: (ctx: PageContext) => void
|
||||
onAfterScanPages?: (ctx: PageContext) => void
|
||||
onBeforeMergePageMetaData?: (ctx: PageContext) => void
|
||||
onAfterMergePageMetaData?: (ctx: PageContext) => void
|
||||
onBeforeWriteFile?: (ctx: PageContext) => void
|
||||
onAfterWriteFile?: (ctx: PageContext) => void
|
||||
}
|
||||
```
|
||||
|
||||
## Usage with Layouts
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
definePage({
|
||||
layout: 'default', // Specify layout
|
||||
middlewares: ['auth'],
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-pages
|
||||
- https://uni-helper.js.org/vite-plugin-uni-pages
|
||||
-->
|
||||
119
.claude/skills/uni-helper/references/plugin-platform-modifier.md
Normal file
119
.claude/skills/uni-helper/references/plugin-platform-modifier.md
Normal file
@@ -0,0 +1,119 @@
|
||||
---
|
||||
name: vite-plugin-uni-platform-modifier
|
||||
description: Platform modifiers for attributes and directives in uni-app - optimize bundle size by removing unused platform code
|
||||
---
|
||||
|
||||
# vite-plugin-uni-platform-modifier
|
||||
|
||||
Add platform modifiers to attributes and directives for conditional compilation at the template level. Reduces bundle size by removing code for other platforms.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-platform-modifier
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import UniPlatformModifier from '@uni-helper/vite-plugin-uni-platform-modifier'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [UniPlatformModifier(), Uni()],
|
||||
})
|
||||
```
|
||||
|
||||
## Platform Modifiers
|
||||
|
||||
### Directive Modifiers
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Only render on H5 -->
|
||||
<view v-if.h5="condition">H5 only content</view>
|
||||
|
||||
<!-- Only render on WeChat -->
|
||||
<button v-if.mp-weixin="true">WeChat specific</button>
|
||||
|
||||
<!-- Only render on App -->
|
||||
<native-view v-if.app="true">Native view</native-view>
|
||||
|
||||
<!-- Platform-specific event -->
|
||||
<view @click.h5="handleH5Click" @click.mp-weixin="handleWeChatClick">
|
||||
Platform-specific click
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Attribute Modifiers
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- Different classes per platform -->
|
||||
<view class.h5="h5-container" class.mp-weixin="wechat-container">
|
||||
Content
|
||||
</view>
|
||||
|
||||
<!-- Platform-specific styles -->
|
||||
<view :style.h5="{ padding: '20px' }" :style.app="{ padding: '10px' }">
|
||||
Styled content
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
| Modifier | Platform |
|
||||
|----------|----------|
|
||||
| `.h5` | H5/Web |
|
||||
| `.mp-weixin` | WeChat Mini Program |
|
||||
| `.mp-alipay` | Alipay Mini Program |
|
||||
| `.mp-baidu` | Baidu Smart Program |
|
||||
| `.mp-toutiao` | Douyin Mini Program |
|
||||
| `.mp-qq` | QQ Mini Program |
|
||||
| `.app` | iOS/Android App |
|
||||
|
||||
## How It Works
|
||||
|
||||
The plugin transforms templates at build time:
|
||||
|
||||
```vue
|
||||
<!-- Source -->
|
||||
<view v-if.h5="show">H5 Only</view>
|
||||
|
||||
<!-- Transformed for H5 build -->
|
||||
<view v-if="show">H5 Only</view>
|
||||
|
||||
<!-- Removed for non-H5 builds -->
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
- Platform-specific UI components
|
||||
- Different interactions per platform
|
||||
- Platform-optimized styles
|
||||
- Conditional event handlers
|
||||
|
||||
## Combining with Other Plugins
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UniComponents(),
|
||||
UniPages(),
|
||||
UniPlatform(), // File-based platform
|
||||
UniPlatformModifier(), // Directive/attribute modifiers
|
||||
Uni(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-platform-modifier
|
||||
- https://uni-helper.js.org/vite-plugin-uni-platform-modifier
|
||||
-->
|
||||
105
.claude/skills/uni-helper/references/plugin-platform.md
Normal file
105
.claude/skills/uni-helper/references/plugin-platform.md
Normal file
@@ -0,0 +1,105 @@
|
||||
---
|
||||
name: vite-plugin-uni-platform
|
||||
description: File-based platform compilation for uni-app - compile different files based on target platform
|
||||
---
|
||||
|
||||
# vite-plugin-uni-platform
|
||||
|
||||
Compile different files based on target platform using file naming conventions. Supports platform-specific implementations without conditional compilation.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/vite-plugin-uni-platform
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [UniPlatform(), Uni()],
|
||||
})
|
||||
```
|
||||
|
||||
## File Naming Convention
|
||||
|
||||
Use platform suffixes in filenames:
|
||||
|
||||
```
|
||||
src/
|
||||
utils/
|
||||
request.ts # Default implementation
|
||||
request.h5.ts # H5-specific
|
||||
request.mp-weixin.ts # WeChat Mini Program
|
||||
request.app.ts # App (iOS/Android)
|
||||
```
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
| Suffix | Platform |
|
||||
|--------|----------|
|
||||
| `.h5.ts` | H5/Web |
|
||||
| `.mp-weixin.ts` | WeChat Mini Program |
|
||||
| `.mp-alipay.ts` | Alipay Mini Program |
|
||||
| `.mp-baidu.ts` | Baidu Smart Program |
|
||||
| `.mp-toutiao.ts` | Douyin Mini Program |
|
||||
| `.mp-qq.ts` | QQ Mini Program |
|
||||
| `.mp-kuaishou.ts` | Kuaishou Mini Program |
|
||||
| `.app.ts` | iOS/Android App |
|
||||
| `.app-plus.ts` | App (alternative) |
|
||||
| `.harmony` | HarmonyOS |
|
||||
|
||||
## Import Usage
|
||||
|
||||
Import without the platform suffix:
|
||||
|
||||
```ts
|
||||
// This automatically resolves to the correct platform version
|
||||
import { request } from './utils/request'
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
// utils/request.ts - Default implementation
|
||||
export const request = (options: RequestOptions) => {
|
||||
return uni.request(options)
|
||||
}
|
||||
|
||||
// utils/request.h5.ts - H5 with axios
|
||||
import axios from 'axios'
|
||||
|
||||
export const request = (options: RequestOptions) => {
|
||||
return axios.request(options)
|
||||
}
|
||||
|
||||
// utils/request.mp-weixin.ts - WeChat specific
|
||||
export const request = (options: RequestOptions) => {
|
||||
// Add WeChat-specific headers
|
||||
return uni.request({
|
||||
...options,
|
||||
header: {
|
||||
...options.header,
|
||||
'X-Platform': 'weixin',
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
- Cleaner code without `#ifdef` conditions
|
||||
- Type-safe platform implementations
|
||||
- Tree-shaking removes unused platform code
|
||||
- Better IDE support and navigation
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vite-plugin-uni-platform
|
||||
- https://uni-helper.js.org/vite-plugin-uni-platform
|
||||
-->
|
||||
153
.claude/skills/uni-helper/references/starter-create-uni.md
Normal file
153
.claude/skills/uni-helper/references/starter-create-uni.md
Normal file
@@ -0,0 +1,153 @@
|
||||
---
|
||||
name: create-uni
|
||||
description: CLI scaffolding tool for creating uni-app projects with best practices
|
||||
---
|
||||
|
||||
# create-uni
|
||||
|
||||
Interactive CLI tool for scaffolding uni-app projects. Quickly create projects with your choice of templates, plugins, and UI libraries.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# Create new project
|
||||
npm create uni@latest
|
||||
|
||||
# With project name
|
||||
npm create uni@latest my-project
|
||||
|
||||
# With options
|
||||
npm create uni@latest my-project --ts --template vitesse -m pinia -u wot
|
||||
```
|
||||
|
||||
## CLI Options
|
||||
|
||||
| Option | Shorthand | Description |
|
||||
|--------|-----------|-------------|
|
||||
| `--template` | `-t` | Select project template |
|
||||
| `--typescript` | `--ts` | Enable TypeScript |
|
||||
| `--eslint` | `-e` | Add ESLint |
|
||||
| `--plugin` | `-p` | Add Vite plugins |
|
||||
| `--module` | `-m` | Add functional modules |
|
||||
| `--ui` | `-u` | Add UI component library |
|
||||
| `--gui` | - | Launch GUI interface |
|
||||
| `--info` | - | Show project info |
|
||||
|
||||
## Templates
|
||||
|
||||
| Template | Description | Value |
|
||||
|----------|-------------|-------|
|
||||
| Vitesse Uni App | Vite + uni-app starter with best practices | `vitesse` |
|
||||
| Wot Starter | Based on vitesse with wot-ui | `wot-starter` |
|
||||
| Wot Starter Retail | Retail/e-commerce template | `wot-starter-retail` |
|
||||
| Unisave | Web-first uni-app development | `unisave` |
|
||||
| TMUI 3.2 | Enterprise component library | `tmui32` |
|
||||
| uView Pro Starter | uView Pro quick start | `uview-pro-starter` |
|
||||
| uView Pro Demo | uView Pro full demo | `uview-pro-demo` |
|
||||
|
||||
## Available Plugins
|
||||
|
||||
| Plugin | CLI Value | Description |
|
||||
|--------|-----------|-------------|
|
||||
| vite-plugin-uni-components | `import` | Auto component import |
|
||||
| vite-plugin-uni-pages | `pages` | File-based routing |
|
||||
| vite-plugin-uni-layouts | `layouts` | Nuxt-like layouts |
|
||||
| vite-plugin-uni-manifest | `manifest` | TypeScript manifest |
|
||||
| vite-plugin-uni-platform | `filePlatform` | Platform-specific files |
|
||||
| vite-plugin-uni-platform-modifier | `platformModifier` | Platform modifiers |
|
||||
| vite-plugin-uni-middleware | `middleware` | Route middleware |
|
||||
| uni-ku-root | `root` | Virtual root component |
|
||||
|
||||
## Available Modules
|
||||
|
||||
| Module | CLI Value | Description |
|
||||
|--------|-----------|-------------|
|
||||
| Pinia | `pinia` | State management |
|
||||
| UnoCSS | `unocss` | Atomic CSS |
|
||||
| uni-network | `uniNetwork` | HTTP client |
|
||||
| uni-use | `uniUse` | Composable utilities |
|
||||
| uni-promises | `uniPromises` | Promise wrappers |
|
||||
| Uni ECharts | `uniEcharts` | Chart component |
|
||||
| z-paging | `zPaging` | Pagination component |
|
||||
|
||||
## UI Libraries
|
||||
|
||||
| UI Library | CLI Value | Description |
|
||||
|------------|-----------|-------------|
|
||||
| Uni UI | `uni` | Official DCloud UI |
|
||||
| Wot Design Uni | `wot` | Lightweight, beautiful |
|
||||
| uView Pro | `uview-pro` | Vue 3 + TypeScript |
|
||||
| NutUI Uniapp | `nut` | JD style, e-commerce |
|
||||
| Skiyee UI | `skiyee` | Unique design language |
|
||||
| UV UI | `uv` | Multi-platform |
|
||||
| Ano UI | `ano` | UnoCSS-based |
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic TypeScript Project
|
||||
|
||||
```bash
|
||||
npm create uni@latest my-app --ts
|
||||
```
|
||||
|
||||
### With Vitesse Template
|
||||
|
||||
```bash
|
||||
npm create uni@latest my-app --ts --template vitesse
|
||||
```
|
||||
|
||||
### Full-Featured Setup
|
||||
|
||||
```bash
|
||||
npm create uni@latest my-app \
|
||||
--ts \
|
||||
--template vitesse \
|
||||
-p pages -p layouts -p import \
|
||||
-m pinia -m unocss -m uniUse \
|
||||
-u wot \
|
||||
-e
|
||||
```
|
||||
|
||||
### GUI Mode
|
||||
|
||||
```bash
|
||||
npm create uni@latest --gui
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
Created projects follow this structure:
|
||||
|
||||
```
|
||||
my-project/
|
||||
├── src/
|
||||
│ ├── components/ # Vue components
|
||||
│ ├── composables/ # Composable functions
|
||||
│ ├── layouts/ # Layout components (if layouts plugin)
|
||||
│ ├── pages/ # Page components
|
||||
│ ├── static/ # Static assets
|
||||
│ ├── stores/ # Pinia stores (if pinia)
|
||||
│ ├── App.vue
|
||||
│ ├── main.ts
|
||||
│ ├── manifest.config.ts # (if manifest plugin)
|
||||
│ └── pages.config.ts # (if pages plugin)
|
||||
├── index.html
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
├── vite.config.ts
|
||||
└── uno.config.ts # (if unocss)
|
||||
```
|
||||
|
||||
## Post-Creation
|
||||
|
||||
```bash
|
||||
cd my-project
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/create-uni
|
||||
- https://uni-helper.js.org/create-uni
|
||||
-->
|
||||
263
.claude/skills/uni-helper/references/starter-vitesse.md
Normal file
263
.claude/skills/uni-helper/references/starter-vitesse.md
Normal file
@@ -0,0 +1,263 @@
|
||||
---
|
||||
name: vitesse-uni-app
|
||||
description: Vite-powered opinionated uni-app starter template with best practices
|
||||
---
|
||||
|
||||
# vitesse-uni-app
|
||||
|
||||
Opinionated uni-app starter template powered by Vite. Includes best practices, pre-configured tooling, and modern development experience.
|
||||
|
||||
## Features
|
||||
|
||||
- ⚡️ **Vite** - Fast development and building
|
||||
- 🌍 **uni-app** - Cross-platform development
|
||||
- 🖖 **Vue 3** - Composition API, `<script setup>`
|
||||
- 🔷 **TypeScript** - Type safety
|
||||
- 🎨 **UnoCSS** - Atomic CSS
|
||||
- 📦 **Auto Import** - Components and composables
|
||||
- 🗂 **File-based Routing** - vite-plugin-uni-pages
|
||||
- 📐 **Layout System** - Nuxt-like layouts
|
||||
- 🔧 **ESLint** - Code linting
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Create with create-uni
|
||||
npm create uni@latest my-app --template vitesse
|
||||
|
||||
# Or clone directly
|
||||
git clone https://github.com/uni-helper/vitesse-uni-app.git my-app
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
vitesse-uni-app/
|
||||
├── src/
|
||||
│ ├── components/ # Auto-imported components
|
||||
│ ├── composables/ # Auto-imported composables
|
||||
│ ├── layouts/ # Layout components
|
||||
│ │ ├── default.vue
|
||||
│ │ └── home.vue
|
||||
│ ├── pages/ # File-based routing
|
||||
│ │ ├── index.vue
|
||||
│ │ └── about/
|
||||
│ │ └── index.vue
|
||||
│ ├── static/ # Static assets
|
||||
│ ├── stores/ # Pinia stores
|
||||
│ ├── styles/ # Global styles
|
||||
│ ├── App.vue
|
||||
│ ├── main.ts
|
||||
│ ├── manifest.config.ts # TypeScript manifest
|
||||
│ └── pages.config.ts # Global pages config
|
||||
├── types/ # Type definitions
|
||||
├── index.html
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
├── vite.config.ts
|
||||
├── uno.config.ts
|
||||
└── eslint.config.js
|
||||
```
|
||||
|
||||
## Pre-configured Plugins
|
||||
|
||||
The template includes these pre-configured plugins:
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UniComponents({
|
||||
resolvers: [AnoUIResolver()],
|
||||
}),
|
||||
UniPages(),
|
||||
UniLayouts(),
|
||||
UniManifest(),
|
||||
Uni(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Auto Imports
|
||||
|
||||
### Components
|
||||
|
||||
Components in `src/components/` are auto-imported:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- No import needed -->
|
||||
<MyButton />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Composables
|
||||
|
||||
Files in `src/composables/` are auto-imported:
|
||||
|
||||
```ts
|
||||
// src/composables/useCounter.ts
|
||||
export function useCounter() {
|
||||
const count = ref(0)
|
||||
const inc = () => count.value++
|
||||
return { count, inc }
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// No import needed
|
||||
const { count, inc } = useCounter()
|
||||
</script>
|
||||
```
|
||||
|
||||
### Vue APIs
|
||||
|
||||
Vue APIs are auto-imported:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
// No need to import ref, computed, etc.
|
||||
const count = ref(0)
|
||||
const doubled = computed(() => count.value * 2)
|
||||
</script>
|
||||
```
|
||||
|
||||
## Routing
|
||||
|
||||
File-based routing with pages in `src/pages/`:
|
||||
|
||||
```
|
||||
pages/
|
||||
├── index.vue # /pages/index/index
|
||||
├── about.vue # /pages/about/index
|
||||
└── user/
|
||||
├── index.vue # /pages/user/index
|
||||
└── [id].vue # /pages/user/:id
|
||||
```
|
||||
|
||||
### Page Configuration
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
definePage({
|
||||
style: {
|
||||
navigationBarTitleText: 'About',
|
||||
},
|
||||
layout: 'default',
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Layouts
|
||||
|
||||
Create layouts in `src/layouts/`:
|
||||
|
||||
```vue
|
||||
<!-- src/layouts/default.vue -->
|
||||
<template>
|
||||
<view class="layout">
|
||||
<slot name="header" />
|
||||
<slot />
|
||||
<slot name="footer" />
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
Apply in pages:
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
definePage({
|
||||
layout: 'default',
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template #header>
|
||||
<NavBar />
|
||||
</template>
|
||||
<div>Content</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Styling with UnoCSS
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<view class="p-32 bg-gray-100">
|
||||
<text class="text-32 font-bold text-primary">
|
||||
Styled with UnoCSS
|
||||
</text>
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## State Management with Pinia
|
||||
|
||||
```ts
|
||||
// src/stores/user.ts
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const name = ref('')
|
||||
const isLoggedIn = computed(() => !!name.value)
|
||||
|
||||
function login(userName: string) {
|
||||
name.value = userName
|
||||
}
|
||||
|
||||
return { name, isLoggedIn, login }
|
||||
})
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const user = useUserStore()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Data Fetching
|
||||
|
||||
```vue
|
||||
<script setup>
|
||||
const { data: users, pending, error } = useFetch('/api/users')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<view v-if="pending">Loading...</view>
|
||||
<view v-else-if="error">Error: {{ error.message }}</view>
|
||||
<view v-else>
|
||||
<view v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
### Build for production
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Platform-specific builds
|
||||
|
||||
```bash
|
||||
# H5
|
||||
npm run build:h5
|
||||
|
||||
# WeChat Mini Program
|
||||
npm run build:mp-weixin
|
||||
|
||||
# App
|
||||
npm run build:app
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/vitesse-uni-app
|
||||
- https://uni-helper.js.org/vitesse-uni-app
|
||||
-->
|
||||
155
.claude/skills/uni-helper/references/util-uni-env.md
Normal file
155
.claude/skills/uni-helper/references/util-uni-env.md
Normal file
@@ -0,0 +1,155 @@
|
||||
---
|
||||
name: uni-env
|
||||
description: Environment detection utilities for uni-app - detect platform at runtime
|
||||
---
|
||||
|
||||
# uni-env
|
||||
|
||||
Runtime environment detection utilities for uni-app. Detect the current platform in a type-safe way.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i @uni-helper/uni-env
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { isH5, isMpWeixin, isApp, isMp } from '@uni-helper/uni-env'
|
||||
|
||||
if (isH5) {
|
||||
console.log('Running in H5')
|
||||
}
|
||||
|
||||
if (isMpWeixin) {
|
||||
console.log('Running in WeChat Mini Program')
|
||||
}
|
||||
```
|
||||
|
||||
## Available Detectors
|
||||
|
||||
### Platform Groups
|
||||
|
||||
| Detector | Description |
|
||||
|----------|-------------|
|
||||
| `isH5` | H5/Web platform |
|
||||
| `isApp` | iOS/Android App |
|
||||
| `isMp` | Any Mini Program |
|
||||
| `isQuickapp` | Quick App |
|
||||
|
||||
### Mini Program Detectors
|
||||
|
||||
| Detector | Description |
|
||||
|----------|-------------|
|
||||
| `isMpWeixin` | WeChat Mini Program |
|
||||
| `isMpAlipay` | Alipay Mini Program |
|
||||
| `isMpBaidu` | Baidu Smart Program |
|
||||
| `isMpToutiao` | Douyin Mini Program |
|
||||
| `isMpQQ` | QQ Mini Program |
|
||||
| `isMpKuaishou` | Kuaishou Mini Program |
|
||||
| `isMpJd` | JD Mini Program |
|
||||
| `isMpHarmony` | HarmonyOS Meta Service |
|
||||
| `isMpLark` | Feishu/Lark Mini Program |
|
||||
|
||||
### Development Detectors
|
||||
|
||||
| Detector | Description |
|
||||
|----------|-------------|
|
||||
| `isDev` | Development environment |
|
||||
| `isProd` | Production environment |
|
||||
|
||||
## Use Cases
|
||||
|
||||
### Conditional Logic
|
||||
|
||||
```ts
|
||||
import { isH5, isMpWeixin, isApp } from '@uni-helper/uni-env'
|
||||
|
||||
function getStorageAdapter() {
|
||||
if (isH5) {
|
||||
return new LocalStorageAdapter()
|
||||
}
|
||||
if (isMpWeixin) {
|
||||
return new WechatStorageAdapter()
|
||||
}
|
||||
if (isApp) {
|
||||
return new NativeStorageAdapter()
|
||||
}
|
||||
return new UniStorageAdapter()
|
||||
}
|
||||
```
|
||||
|
||||
### Platform-Specific Features
|
||||
|
||||
```ts
|
||||
import { isH5, isMpWeixin } from '@uni-helper/uni-env'
|
||||
|
||||
function share(content: ShareContent) {
|
||||
if (isMpWeixin) {
|
||||
// Use WeChat share API
|
||||
wx.showShareMenu({ withShareTicket: true })
|
||||
} else if (isH5) {
|
||||
// Use Web Share API
|
||||
navigator.share({
|
||||
title: content.title,
|
||||
url: content.url,
|
||||
})
|
||||
} else {
|
||||
// Use uni-app generic share
|
||||
uni.share({
|
||||
title: content.title,
|
||||
path: content.path,
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### With definePage
|
||||
|
||||
```ts
|
||||
import { isH5 } from '@uni-helper/uni-env'
|
||||
|
||||
definePage(() => {
|
||||
const title = isH5 ? 'H5 Version' : 'Mobile Version'
|
||||
|
||||
return {
|
||||
style: {
|
||||
navigationBarTitleText: title,
|
||||
},
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Important Note
|
||||
|
||||
This package is primarily for **plugin developers**. For runtime conditional compilation, use uni-app's [official conditional compilation](https://uniapp.dcloud.net.cn/tutorial/platform.html#preprocessor) with `/* #ifdef */` comments.
|
||||
|
||||
For better conditional compilation support, consider using [unplugin-preprocessor-directives](https://github.com/KeJunMao/unplugin-preprocessor-directives).
|
||||
|
||||
## Comparison with Conditional Compilation
|
||||
|
||||
```ts
|
||||
// Runtime detection (uni-env)
|
||||
import { isH5 } from '@uni-helper/uni-env'
|
||||
if (isH5) {
|
||||
// This code exists in all builds
|
||||
doH5Thing()
|
||||
}
|
||||
|
||||
// Build-time conditional compilation
|
||||
// #ifdef H5
|
||||
doH5Thing()
|
||||
// #endif
|
||||
// This code only exists in H5 builds
|
||||
```
|
||||
|
||||
Choose based on your needs:
|
||||
- Use **uni-env** for runtime detection when you need the same bundle for multiple platforms
|
||||
- Use **conditional compilation** for build-time optimization and smaller bundles
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/uni-env
|
||||
- https://uni-helper.js.org/uni-env
|
||||
-->
|
||||
175
.claude/skills/uni-helper/references/util-unocss-preset.md
Normal file
175
.claude/skills/uni-helper/references/util-unocss-preset.md
Normal file
@@ -0,0 +1,175 @@
|
||||
---
|
||||
name: unocss-preset-uni
|
||||
description: UnoCSS preset for uni-app with platform-specific utilities and rpx support
|
||||
---
|
||||
|
||||
# unocss-preset-uni
|
||||
|
||||
UnoCSS preset designed for uni-app development. Provides utilities for rpx units and platform-specific styling.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm i -D @uni-helper/unocss-preset-uni
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import { defineConfig } from 'unocss'
|
||||
import { presetUni } from '@uni-helper/unocss-preset-uni'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetUni(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **rpx support**: Automatic conversion to rpx units
|
||||
- **Platform variants**: Style targeting specific platforms
|
||||
- **Safe area utilities**: Handle notches and safe areas
|
||||
- **Compatible with**: Mini programs, H5, and App
|
||||
|
||||
## RPX Utilities
|
||||
|
||||
The preset automatically converts pixel values to rpx:
|
||||
|
||||
```html
|
||||
<!-- These generate rpx units -->
|
||||
<view class="w-100"></view> <!-- width: 100rpx -->
|
||||
<view class="h-50"></view> <!-- height: 50rpx -->
|
||||
<view class="m-20"></view> <!-- margin: 20rpx -->
|
||||
<view class="p-16"></view> <!-- padding: 16rpx -->
|
||||
<view class="text-32"></view> <!-- font-size: 32rpx -->
|
||||
```
|
||||
|
||||
## Platform Variants
|
||||
|
||||
Apply styles to specific platforms:
|
||||
|
||||
```html
|
||||
<!-- Only apply on H5 -->
|
||||
<view class="h5:bg-red"></view>
|
||||
|
||||
<!-- Only apply on WeChat -->
|
||||
<view class="mp-weixin:bg-blue"></view>
|
||||
|
||||
<!-- Only apply on App -->
|
||||
<view class="app:bg-green"></view>
|
||||
|
||||
<!-- Combine with responsive -->
|
||||
<view class="h5:p-20 mp-weixin:p-10"></view>
|
||||
```
|
||||
|
||||
## Safe Area Utilities
|
||||
|
||||
```html
|
||||
<!-- Safe area padding -->
|
||||
<view class="pt-safe"></view> <!-- padding-top: env(safe-area-inset-top) -->
|
||||
<view class="pb-safe"></view> <!-- padding-bottom: env(safe-area-inset-bottom) -->
|
||||
<view class="px-safe"></view> <!-- padding-x with safe area -->
|
||||
|
||||
<!-- Safe area margin -->
|
||||
<view class="mt-safe"></view>
|
||||
<view class="mb-safe"></view>
|
||||
|
||||
<!-- Full safe area -->
|
||||
<view class="safe-area"></view>
|
||||
```
|
||||
|
||||
## Tab Bar Utilities
|
||||
|
||||
```html
|
||||
<!-- Padding for tab bar -->
|
||||
<view class="pb-tabbar"></view>
|
||||
|
||||
<!-- Margin for tab bar -->
|
||||
<view class="mb-tabbar"></view>
|
||||
```
|
||||
|
||||
## Status Bar Utilities
|
||||
|
||||
```html
|
||||
<!-- Status bar height -->
|
||||
<view class="h-statusbar"></view>
|
||||
<view class="pt-statusbar"></view>
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import { defineConfig } from 'unocss'
|
||||
import { presetUni } from '@uni-helper/unocss-preset-uni'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetUni({
|
||||
// rpx base width (default: 750)
|
||||
baseWidth: 750,
|
||||
|
||||
// Enable platform variants
|
||||
platform: true,
|
||||
|
||||
// Enable safe area utilities
|
||||
safeArea: true,
|
||||
|
||||
// Custom platforms
|
||||
platforms: ['mp-weixin', 'mp-alipay', 'h5', 'app'],
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## With Vite
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import Uni from '@dcloudio/vite-plugin-uni'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UnoCSS(),
|
||||
Uni(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<view class="page bg-gray-100">
|
||||
<!-- Status bar spacing -->
|
||||
<view class="h-statusbar"></view>
|
||||
|
||||
<!-- Header with safe area -->
|
||||
<view class="px-32 pt-safe flex items-center justify-between">
|
||||
<text class="text-36 font-bold">Title</text>
|
||||
</view>
|
||||
|
||||
<!-- Content -->
|
||||
<view class="p-32 flex flex-col gap-20">
|
||||
<!-- Platform-specific styling -->
|
||||
<view class="card h5:shadow-lg mp-weixin:border">
|
||||
<text class="text-28 text-gray-800">Content</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- Bottom safe area for devices with notches -->
|
||||
<view class="pb-safe"></view>
|
||||
</view>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://github.com/uni-helper/unocss-preset-uni
|
||||
- https://uni-helper.js.org/unocss-preset-uni
|
||||
-->
|
||||
5
.claude/skills/unocss/GENERATION.md
Normal file
5
.claude/skills/unocss/GENERATION.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Generation Info
|
||||
|
||||
- **Source:** `sources/unocss`
|
||||
- **Git SHA:** `2f7f267d0cc0c43d44357208aabb35b049359a08`
|
||||
- **Generated:** 2026-01-28
|
||||
21
.claude/skills/unocss/LICENSE.md
Normal file
21
.claude/skills/unocss/LICENSE.md
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025-PRESENT Anthony Fu <https://github.com/antfu>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
64
.claude/skills/unocss/SKILL.md
Normal file
64
.claude/skills/unocss/SKILL.md
Normal file
@@ -0,0 +1,64 @@
|
||||
---
|
||||
name: unocss
|
||||
description: UnoCSS instant atomic CSS engine, superset of Tailwind CSS. Use when configuring UnoCSS, writing utility rules, shortcuts, or working with presets like Wind, Icons, Attributify.
|
||||
metadata:
|
||||
author: Anthony Fu
|
||||
version: "2026.1.28"
|
||||
source: Generated from https://github.com/unocss/unocss, scripts located at https://github.com/antfu/skills
|
||||
---
|
||||
|
||||
UnoCSS is an instant atomic CSS engine designed to be flexible and extensible. The core is un-opinionated - all CSS utilities are provided via presets. It's a superset of Tailwind CSS, so you can reuse your Tailwind knowledge for basic syntax usage.
|
||||
|
||||
**Important:** Before writing UnoCSS code, agents should check for `uno.config.*` or `unocss.config.*` files in the project root to understand what presets, rules, and shortcuts are available. If the project setup is unclear, avoid using attributify mode and other advanced features - stick to basic `class` usage.
|
||||
|
||||
> The skill is based on UnoCSS 66.x, generated at 2026-01-28.
|
||||
|
||||
## Core
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Configuration | Config file setup and all configuration options | [core-config](references/core-config.md) |
|
||||
| Rules | Static and dynamic rules for generating CSS utilities | [core-rules](references/core-rules.md) |
|
||||
| Shortcuts | Combine multiple rules into single shorthands | [core-shortcuts](references/core-shortcuts.md) |
|
||||
| Theme | Theming system for colors, breakpoints, and design tokens | [core-theme](references/core-theme.md) |
|
||||
| Variants | Apply variations like hover:, dark:, responsive to rules | [core-variants](references/core-variants.md) |
|
||||
| Extracting | How UnoCSS extracts utilities from source code | [core-extracting](references/core-extracting.md) |
|
||||
| Safelist & Blocklist | Force include or exclude specific utilities | [core-safelist](references/core-safelist.md) |
|
||||
| Layers & Preflights | CSS layer ordering and raw CSS injection | [core-layers](references/core-layers.md) |
|
||||
|
||||
## Presets
|
||||
|
||||
### Main Presets
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Preset Wind3 | Tailwind CSS v3 / Windi CSS compatible preset (most common) | [preset-wind3](references/preset-wind3.md) |
|
||||
| Preset Wind4 | Tailwind CSS v4 compatible preset with modern CSS features | [preset-wind4](references/preset-wind4.md) |
|
||||
| Preset Mini | Minimal preset with essential utilities for custom builds | [preset-mini](references/preset-mini.md) |
|
||||
|
||||
### Feature Presets
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Preset Icons | Pure CSS icons using Iconify with any icon set | [preset-icons](references/preset-icons.md) |
|
||||
| Preset Attributify | Group utilities in HTML attributes instead of class | [preset-attributify](references/preset-attributify.md) |
|
||||
| Preset Typography | Prose classes for typographic defaults | [preset-typography](references/preset-typography.md) |
|
||||
| Preset Web Fonts | Easy Google Fonts and other web fonts integration | [preset-web-fonts](references/preset-web-fonts.md) |
|
||||
| Preset Tagify | Use utilities as HTML tag names | [preset-tagify](references/preset-tagify.md) |
|
||||
| Preset Rem to Px | Convert rem units to px for utilities | [preset-rem-to-px](references/preset-rem-to-px.md) |
|
||||
|
||||
## Transformers
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Variant Group | Shorthand for grouping utilities with common prefixes | [transformer-variant-group](references/transformer-variant-group.md) |
|
||||
| Directives | CSS directives: @apply, @screen, theme(), icon() | [transformer-directives](references/transformer-directives.md) |
|
||||
| Compile Class | Compile multiple classes into one hashed class | [transformer-compile-class](references/transformer-compile-class.md) |
|
||||
| Attributify JSX | Support valueless attributify in JSX/TSX | [transformer-attributify-jsx](references/transformer-attributify-jsx.md) |
|
||||
|
||||
## Integrations
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Vite Integration | Setting up UnoCSS with Vite and framework-specific tips | [integrations-vite](references/integrations-vite.md) |
|
||||
| Nuxt Integration | UnoCSS module for Nuxt applications | [integrations-nuxt](references/integrations-nuxt.md) |
|
||||
5
.claude/skills/unocss/SYNC.md
Normal file
5
.claude/skills/unocss/SYNC.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Sync Info
|
||||
|
||||
- **Source:** `vendor/antfu/skills/unocss`
|
||||
- **Git SHA:** `4086f59fa12d308fb05592ca8ce1704fbb940aa3`
|
||||
- **Synced:** 2026-01-30
|
||||
187
.claude/skills/unocss/references/core-config.md
Normal file
187
.claude/skills/unocss/references/core-config.md
Normal file
@@ -0,0 +1,187 @@
|
||||
---
|
||||
name: unocss-configuration
|
||||
description: Config file setup and all configuration options for UnoCSS
|
||||
---
|
||||
|
||||
# UnoCSS Configuration
|
||||
|
||||
UnoCSS is configured via a dedicated config file in your project root.
|
||||
|
||||
## Config File
|
||||
|
||||
**Recommended:** Use a dedicated `uno.config.ts` file for best IDE support and HMR.
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import {
|
||||
defineConfig,
|
||||
presetAttributify,
|
||||
presetIcons,
|
||||
presetTypography,
|
||||
presetWebFonts,
|
||||
presetWind3,
|
||||
transformerDirectives,
|
||||
transformerVariantGroup
|
||||
} from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
shortcuts: [
|
||||
// ...
|
||||
],
|
||||
theme: {
|
||||
colors: {
|
||||
// ...
|
||||
}
|
||||
},
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetAttributify(),
|
||||
presetIcons(),
|
||||
presetTypography(),
|
||||
presetWebFonts({
|
||||
fonts: {
|
||||
// ...
|
||||
},
|
||||
}),
|
||||
],
|
||||
transformers: [
|
||||
transformerDirectives(),
|
||||
transformerVariantGroup(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
UnoCSS automatically looks for `uno.config.{js,ts,mjs,mts}` or `unocss.config.{js,ts,mjs,mts}` in the project root.
|
||||
|
||||
## Key Configuration Options
|
||||
|
||||
### rules
|
||||
Define CSS utility rules. Later entries have higher priority.
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
['m-1', { margin: '0.25rem' }],
|
||||
[/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
|
||||
]
|
||||
```
|
||||
|
||||
### shortcuts
|
||||
Combine multiple rules into a single shorthand.
|
||||
|
||||
```ts
|
||||
shortcuts: {
|
||||
'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
|
||||
}
|
||||
```
|
||||
|
||||
### theme
|
||||
Theme object for design tokens shared between rules.
|
||||
|
||||
```ts
|
||||
theme: {
|
||||
colors: {
|
||||
brand: '#942192',
|
||||
},
|
||||
breakpoints: {
|
||||
sm: '640px',
|
||||
md: '768px',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### presets
|
||||
Predefined configurations bundling rules, variants, and themes.
|
||||
|
||||
```ts
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetIcons(),
|
||||
]
|
||||
```
|
||||
|
||||
### transformers
|
||||
Transform source code to support special syntax.
|
||||
|
||||
```ts
|
||||
transformers: [
|
||||
transformerDirectives(),
|
||||
transformerVariantGroup(),
|
||||
]
|
||||
```
|
||||
|
||||
### variants
|
||||
Preprocess selectors with ability to rewrite CSS output.
|
||||
|
||||
### extractors
|
||||
Handle source files and extract utility class names.
|
||||
|
||||
### preflights
|
||||
Inject raw CSS globally.
|
||||
|
||||
### layers
|
||||
Control the order of CSS layers. Default is `0`.
|
||||
|
||||
```ts
|
||||
layers: {
|
||||
'components': -1,
|
||||
'default': 1,
|
||||
'utilities': 2,
|
||||
}
|
||||
```
|
||||
|
||||
### safelist
|
||||
Utilities that are always included in output.
|
||||
|
||||
```ts
|
||||
safelist: ['p-1', 'p-2', 'p-3']
|
||||
```
|
||||
|
||||
### blocklist
|
||||
Utilities that are always excluded.
|
||||
|
||||
```ts
|
||||
blocklist: ['p-1', /^p-[2-4]$/]
|
||||
```
|
||||
|
||||
### content
|
||||
Configure where to extract utilities from.
|
||||
|
||||
```ts
|
||||
content: {
|
||||
pipeline: {
|
||||
include: [/\.(vue|svelte|tsx|html)($|\?)/],
|
||||
},
|
||||
filesystem: ['src/**/*.php'],
|
||||
}
|
||||
```
|
||||
|
||||
### separators
|
||||
Variant separator characters. Default: `[':', '-']`
|
||||
|
||||
### outputToCssLayers
|
||||
Output UnoCSS layers as CSS Cascade Layers.
|
||||
|
||||
```ts
|
||||
outputToCssLayers: true
|
||||
```
|
||||
|
||||
## Specifying Config File Location
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UnoCSS({
|
||||
configFile: '../my-uno.config.ts',
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/guide/config-file
|
||||
- https://unocss.dev/config/
|
||||
-->
|
||||
137
.claude/skills/unocss/references/core-extracting.md
Normal file
137
.claude/skills/unocss/references/core-extracting.md
Normal file
@@ -0,0 +1,137 @@
|
||||
---
|
||||
name: unocss-extracting
|
||||
description: How UnoCSS extracts utilities from source code
|
||||
---
|
||||
|
||||
# Extracting
|
||||
|
||||
UnoCSS searches for utility usages in your codebase and generates CSS on-demand.
|
||||
|
||||
## Content Sources
|
||||
|
||||
### Pipeline Extraction (Vite/Webpack)
|
||||
|
||||
Most efficient - extracts from build tool pipeline.
|
||||
|
||||
**Default file types:** `.jsx`, `.tsx`, `.vue`, `.md`, `.html`, `.svelte`, `.astro`, `.marko`
|
||||
|
||||
**Not included by default:** `.js`, `.ts`
|
||||
|
||||
```ts
|
||||
export default defineConfig({
|
||||
content: {
|
||||
pipeline: {
|
||||
include: [
|
||||
/\.(vue|svelte|[jt]sx|mdx?|astro|html)($|\?)/,
|
||||
'src/**/*.{js,ts}', // Add js/ts
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Filesystem Extraction
|
||||
|
||||
For files not in build pipeline:
|
||||
|
||||
```ts
|
||||
export default defineConfig({
|
||||
content: {
|
||||
filesystem: [
|
||||
'src/**/*.php',
|
||||
'public/*.html',
|
||||
],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Inline Text Extraction
|
||||
|
||||
```ts
|
||||
export default defineConfig({
|
||||
content: {
|
||||
inline: [
|
||||
'<div class="p-4 text-red">Some text</div>',
|
||||
async () => (await fetch('https://example.com')).text(),
|
||||
],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Magic Comments
|
||||
|
||||
### @unocss-include
|
||||
|
||||
Force scan a file:
|
||||
|
||||
```ts
|
||||
// @unocss-include
|
||||
export const classes = {
|
||||
active: 'bg-primary text-white',
|
||||
}
|
||||
```
|
||||
|
||||
### @unocss-ignore
|
||||
|
||||
Skip entire file:
|
||||
|
||||
```ts
|
||||
// @unocss-ignore
|
||||
```
|
||||
|
||||
### @unocss-skip-start / @unocss-skip-end
|
||||
|
||||
Skip specific blocks:
|
||||
|
||||
```html
|
||||
<p class="text-green">Extracted</p>
|
||||
<!-- @unocss-skip-start -->
|
||||
<p class="text-red">NOT extracted</p>
|
||||
<!-- @unocss-skip-end -->
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
UnoCSS works at **build time** - dynamic classes don't work:
|
||||
|
||||
```html
|
||||
<!-- Won't work! -->
|
||||
<div class="p-${size}"></div>
|
||||
```
|
||||
|
||||
### Solutions
|
||||
|
||||
**1. Safelist** - Pre-generate known values:
|
||||
|
||||
```ts
|
||||
safelist: ['p-1', 'p-2', 'p-3', 'p-4']
|
||||
```
|
||||
|
||||
**2. Static mapping** - List combinations statically:
|
||||
|
||||
```ts
|
||||
const colors = {
|
||||
red: 'text-red border-red',
|
||||
blue: 'text-blue border-blue',
|
||||
}
|
||||
```
|
||||
|
||||
**3. Runtime** - Use `@unocss/runtime` for true runtime generation.
|
||||
|
||||
## Custom Extractors
|
||||
|
||||
```ts
|
||||
extractors: [
|
||||
{
|
||||
name: 'my-extractor',
|
||||
extract({ code }) {
|
||||
return code.match(/class:[\w-]+/g) || []
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/guide/extracting
|
||||
-->
|
||||
104
.claude/skills/unocss/references/core-layers.md
Normal file
104
.claude/skills/unocss/references/core-layers.md
Normal file
@@ -0,0 +1,104 @@
|
||||
---
|
||||
name: unocss-layers-preflights
|
||||
description: CSS layer ordering and raw CSS injection
|
||||
---
|
||||
|
||||
# Layers and Preflights
|
||||
|
||||
Control CSS output order and inject global CSS.
|
||||
|
||||
## Layers
|
||||
|
||||
Set layer on rules:
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` }), { layer: 'utilities' }],
|
||||
['btn', { padding: '4px' }], // default layer
|
||||
]
|
||||
```
|
||||
|
||||
### Layer Ordering
|
||||
|
||||
```ts
|
||||
layers: {
|
||||
'components': -1,
|
||||
'default': 1,
|
||||
'utilities': 2,
|
||||
}
|
||||
```
|
||||
|
||||
### Import Layers Separately
|
||||
|
||||
```ts
|
||||
import 'uno:components.css'
|
||||
import 'uno.css'
|
||||
import './my-custom.css'
|
||||
import 'uno:utilities.css'
|
||||
```
|
||||
|
||||
### CSS Cascade Layers
|
||||
|
||||
```ts
|
||||
outputToCssLayers: true
|
||||
|
||||
// Or with custom names
|
||||
outputToCssLayers: {
|
||||
cssLayerName: (layer) => {
|
||||
if (layer === 'default') return 'utilities'
|
||||
if (layer === 'shortcuts') return 'utilities.shortcuts'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Layer Variants
|
||||
|
||||
```html
|
||||
<!-- UnoCSS layer -->
|
||||
<p class="uno-layer-my-layer:text-xl">
|
||||
|
||||
<!-- CSS @layer -->
|
||||
<p class="layer-my-layer:text-xl">
|
||||
```
|
||||
|
||||
## Preflights
|
||||
|
||||
Inject raw CSS globally:
|
||||
|
||||
```ts
|
||||
preflights: [
|
||||
{
|
||||
getCSS: ({ theme }) => `
|
||||
* {
|
||||
color: ${theme.colors.gray?.[700] ?? '#333'};
|
||||
margin: 0;
|
||||
}
|
||||
`,
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
With layer:
|
||||
|
||||
```ts
|
||||
preflights: [
|
||||
{
|
||||
layer: 'base',
|
||||
getCSS: () => `html { font-family: system-ui; }`,
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
## preset-wind4 Layers
|
||||
|
||||
| Layer | Description | Order |
|
||||
|-------|-------------|-------|
|
||||
| `properties` | CSS @property rules | -200 |
|
||||
| `theme` | Theme CSS variables | -150 |
|
||||
| `base` | Reset styles | -100 |
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/config/layers
|
||||
- https://unocss.dev/config/preflights
|
||||
-->
|
||||
166
.claude/skills/unocss/references/core-rules.md
Normal file
166
.claude/skills/unocss/references/core-rules.md
Normal file
@@ -0,0 +1,166 @@
|
||||
---
|
||||
name: unocss-rules
|
||||
description: Static and dynamic rules for generating CSS utilities in UnoCSS
|
||||
---
|
||||
|
||||
# UnoCSS Rules
|
||||
|
||||
Rules define utility classes and the CSS they generate. UnoCSS has many built-in rules via presets and allows custom rules.
|
||||
|
||||
## Static Rules
|
||||
|
||||
Simple mapping from class name to CSS properties:
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
['m-1', { margin: '0.25rem' }],
|
||||
['font-bold', { 'font-weight': 700 }],
|
||||
]
|
||||
```
|
||||
|
||||
Usage: `<div class="m-1">` generates `.m-1 { margin: 0.25rem; }`
|
||||
|
||||
**Note:** Use CSS property syntax with hyphens (e.g., `font-weight` not `fontWeight`). Quote properties with hyphens.
|
||||
|
||||
## Dynamic Rules
|
||||
|
||||
Use RegExp matcher with function body for flexible utilities:
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
// Match m-1, m-2, m-100, etc.
|
||||
[/^m-(\d+)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
|
||||
|
||||
// Access theme and context
|
||||
[/^p-(\d+)$/, (match, ctx) => ({ padding: `${match[1] / 4}rem` })],
|
||||
]
|
||||
```
|
||||
|
||||
The function receives:
|
||||
1. RegExp match result (destructure to get captured groups)
|
||||
2. Context object with `theme`, `symbols`, etc.
|
||||
|
||||
## CSS Fallback Values
|
||||
|
||||
Return 2D array for CSS property fallbacks (browser compatibility):
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
[/^h-(\d+)dvh$/, ([_, d]) => [
|
||||
['height', `${d}vh`],
|
||||
['height', `${d}dvh`],
|
||||
]],
|
||||
]
|
||||
```
|
||||
|
||||
Generates: `.h-100dvh { height: 100vh; height: 100dvh; }`
|
||||
|
||||
## Special Symbols
|
||||
|
||||
Control CSS output with symbols from `@unocss/core`:
|
||||
|
||||
```ts
|
||||
import { symbols } from '@unocss/core'
|
||||
|
||||
rules: [
|
||||
['grid', {
|
||||
[symbols.parent]: '@supports (display: grid)',
|
||||
display: 'grid',
|
||||
}],
|
||||
]
|
||||
```
|
||||
|
||||
### Available Symbols
|
||||
|
||||
| Symbol | Description |
|
||||
|--------|-------------|
|
||||
| `symbols.parent` | Parent wrapper (e.g., `@supports`, `@media`) |
|
||||
| `symbols.selector` | Function to modify the selector |
|
||||
| `symbols.layer` | Set the UnoCSS layer |
|
||||
| `symbols.variants` | Array of variant handlers |
|
||||
| `symbols.shortcutsNoMerge` | Disable merging in shortcuts |
|
||||
| `symbols.noMerge` | Disable rule merging |
|
||||
| `symbols.sort` | Override sorting order |
|
||||
| `symbols.body` | Full control of CSS body |
|
||||
|
||||
## Multi-Selector Rules
|
||||
|
||||
Use generator functions to yield multiple CSS rules:
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
[/^button-(.*)$/, function* ([, color], { symbols }) {
|
||||
yield { background: color }
|
||||
yield {
|
||||
[symbols.selector]: selector => `${selector}:hover`,
|
||||
background: `color-mix(in srgb, ${color} 90%, black)`
|
||||
}
|
||||
}],
|
||||
]
|
||||
```
|
||||
|
||||
Generates both `.button-red { background: red; }` and `.button-red:hover { ... }`
|
||||
|
||||
## Fully Controlled Rules
|
||||
|
||||
Return a string for complete CSS control (advanced):
|
||||
|
||||
```ts
|
||||
import { defineConfig, toEscapedSelector as e } from 'unocss'
|
||||
|
||||
rules: [
|
||||
[/^custom-(.+)$/, ([, name], { rawSelector, theme }) => {
|
||||
const selector = e(rawSelector)
|
||||
return `
|
||||
${selector} { font-size: ${theme.fontSize.sm}; }
|
||||
${selector}::after { content: 'after'; }
|
||||
@media (min-width: ${theme.breakpoints.sm}) {
|
||||
${selector} { font-size: ${theme.fontSize.lg}; }
|
||||
}
|
||||
`
|
||||
}],
|
||||
]
|
||||
```
|
||||
|
||||
**Warning:** Fully controlled rules don't work with variants like `hover:`.
|
||||
|
||||
## Symbols.body for Variant Support
|
||||
|
||||
Use `symbols.body` to keep variant support with custom CSS:
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
['custom-red', {
|
||||
[symbols.body]: `
|
||||
font-size: 1rem;
|
||||
&::after { content: 'after'; }
|
||||
& > .bar { color: red; }
|
||||
`,
|
||||
[symbols.selector]: selector => `:is(${selector})`,
|
||||
}]
|
||||
]
|
||||
```
|
||||
|
||||
## Rule Ordering
|
||||
|
||||
Later rules have higher priority. Dynamic rules output is sorted alphabetically within the group.
|
||||
|
||||
## Rule Merging
|
||||
|
||||
UnoCSS merges rules with identical CSS bodies:
|
||||
|
||||
```html
|
||||
<div class="m-2 hover:m2">
|
||||
```
|
||||
|
||||
Generates:
|
||||
```css
|
||||
.hover\:m2:hover, .m-2 { margin: 0.5rem; }
|
||||
```
|
||||
|
||||
Use `symbols.noMerge` to disable.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/config/rules
|
||||
-->
|
||||
105
.claude/skills/unocss/references/core-safelist.md
Normal file
105
.claude/skills/unocss/references/core-safelist.md
Normal file
@@ -0,0 +1,105 @@
|
||||
---
|
||||
name: unocss-safelist-blocklist
|
||||
description: Force include or exclude specific utilities
|
||||
---
|
||||
|
||||
# Safelist and Blocklist
|
||||
|
||||
Control which utilities are always included or excluded.
|
||||
|
||||
## Safelist
|
||||
|
||||
Utilities always included, regardless of detection:
|
||||
|
||||
```ts
|
||||
export default defineConfig({
|
||||
safelist: [
|
||||
'p-1', 'p-2', 'p-3',
|
||||
// Dynamic generation
|
||||
...Array.from({ length: 4 }, (_, i) => `p-${i + 1}`),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Function Form
|
||||
|
||||
```ts
|
||||
safelist: [
|
||||
'p-1',
|
||||
() => ['m-1', 'm-2'],
|
||||
(context) => {
|
||||
const colors = Object.keys(context.theme.colors || {})
|
||||
return colors.map(c => `bg-${c}-500`)
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
### Common Use Cases
|
||||
|
||||
```ts
|
||||
safelist: [
|
||||
// Dynamic colors from CMS
|
||||
() => ['primary', 'secondary'].flatMap(c => [
|
||||
`bg-${c}`, `text-${c}`, `border-${c}`,
|
||||
]),
|
||||
|
||||
// Component variants
|
||||
() => {
|
||||
const variants = ['primary', 'danger']
|
||||
const sizes = ['sm', 'md', 'lg']
|
||||
return variants.flatMap(v => sizes.map(s => `btn-${v}-${s}`))
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
## Blocklist
|
||||
|
||||
Utilities never generated:
|
||||
|
||||
```ts
|
||||
blocklist: [
|
||||
'p-1', // Exact match
|
||||
/^p-[2-4]$/, // Regex
|
||||
]
|
||||
```
|
||||
|
||||
### With Messages
|
||||
|
||||
```ts
|
||||
blocklist: [
|
||||
['bg-red-500', { message: 'Use bg-red-600 instead' }],
|
||||
[/^text-xs$/, { message: 'Use text-sm for accessibility' }],
|
||||
]
|
||||
```
|
||||
|
||||
## Safelist vs Blocklist
|
||||
|
||||
| Feature | Safelist | Blocklist |
|
||||
|---------|----------|-----------|
|
||||
| Purpose | Always include | Always exclude |
|
||||
| Strings | ✅ | ✅ |
|
||||
| Regex | ❌ | ✅ |
|
||||
| Functions | ✅ | ❌ |
|
||||
|
||||
**Note:** Blocklist wins if utility is in both.
|
||||
|
||||
## Best Practice
|
||||
|
||||
Prefer static mappings over safelist:
|
||||
|
||||
```ts
|
||||
// Better: UnoCSS extracts automatically
|
||||
const sizes = {
|
||||
sm: 'text-sm p-2',
|
||||
md: 'text-base p-4',
|
||||
}
|
||||
|
||||
// Avoid: Large safelist
|
||||
safelist: ['text-sm', 'text-base', 'p-2', 'p-4']
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/config/safelist
|
||||
- https://unocss.dev/guide/extracting
|
||||
-->
|
||||
89
.claude/skills/unocss/references/core-shortcuts.md
Normal file
89
.claude/skills/unocss/references/core-shortcuts.md
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
name: unocss-shortcuts
|
||||
description: Combine multiple utility rules into single shorthand classes
|
||||
---
|
||||
|
||||
# UnoCSS Shortcuts
|
||||
|
||||
Shortcuts combine multiple rules into a single shorthand, inspired by Windi CSS.
|
||||
|
||||
## Static Shortcuts
|
||||
|
||||
Define as an object mapping shortcut names to utility combinations:
|
||||
|
||||
```ts
|
||||
shortcuts: {
|
||||
// Multiple utilities combined
|
||||
'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
|
||||
'btn-green': 'text-white bg-green-500 hover:bg-green-700',
|
||||
// Single utility alias
|
||||
'red': 'text-red-100',
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
```html
|
||||
<button class="btn btn-green">Click me</button>
|
||||
```
|
||||
|
||||
## Dynamic Shortcuts
|
||||
|
||||
Use RegExp matcher with function, similar to dynamic rules:
|
||||
|
||||
```ts
|
||||
shortcuts: [
|
||||
// Static shortcuts can be in array too
|
||||
{
|
||||
btn: 'py-2 px-4 font-semibold rounded-lg shadow-md',
|
||||
},
|
||||
// Dynamic shortcut
|
||||
[/^btn-(.*)$/, ([, c]) => `bg-${c}-400 text-${c}-100 py-2 px-4 rounded-lg`],
|
||||
]
|
||||
```
|
||||
|
||||
Now `btn-green` and `btn-red` generate:
|
||||
|
||||
```css
|
||||
.btn-green {
|
||||
padding: 0.5rem 1rem;
|
||||
--un-bg-opacity: 1;
|
||||
background-color: rgb(74 222 128 / var(--un-bg-opacity));
|
||||
border-radius: 0.5rem;
|
||||
--un-text-opacity: 1;
|
||||
color: rgb(220 252 231 / var(--un-text-opacity));
|
||||
}
|
||||
```
|
||||
|
||||
## Accessing Theme in Shortcuts
|
||||
|
||||
Dynamic shortcuts receive context with theme access:
|
||||
|
||||
```ts
|
||||
shortcuts: [
|
||||
[/^badge-(.*)$/, ([, c], { theme }) => {
|
||||
if (Object.keys(theme.colors).includes(c))
|
||||
return `bg-${c}4:10 text-${c}5 rounded`
|
||||
}],
|
||||
]
|
||||
```
|
||||
|
||||
## Shortcuts Layer
|
||||
|
||||
Shortcuts are output to the `shortcuts` layer by default. Configure with:
|
||||
|
||||
```ts
|
||||
shortcutsLayer: 'my-shortcuts-layer'
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
- Later shortcuts have higher priority
|
||||
- Shortcuts can reference other shortcuts
|
||||
- Dynamic shortcuts work like dynamic rules
|
||||
- Shortcuts are expanded at build time, not runtime
|
||||
- All variants work with shortcuts (`hover:btn`, `dark:btn`, etc.)
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/config/shortcuts
|
||||
-->
|
||||
172
.claude/skills/unocss/references/core-theme.md
Normal file
172
.claude/skills/unocss/references/core-theme.md
Normal file
@@ -0,0 +1,172 @@
|
||||
---
|
||||
name: unocss-theme
|
||||
description: Theming system for colors, breakpoints, and design tokens
|
||||
---
|
||||
|
||||
# UnoCSS Theme
|
||||
|
||||
UnoCSS supports theming similar to Tailwind CSS / Windi CSS. The `theme` property is deep-merged with the default theme.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```ts
|
||||
theme: {
|
||||
colors: {
|
||||
veryCool: '#0000ff', // class="text-very-cool"
|
||||
brand: {
|
||||
primary: 'hsl(var(--hue, 217) 78% 51%)', // class="bg-brand-primary"
|
||||
DEFAULT: '#942192' // class="bg-brand"
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Using Theme in Rules
|
||||
|
||||
Access theme values in dynamic rules:
|
||||
|
||||
```ts
|
||||
rules: [
|
||||
[/^text-(.*)$/, ([, c], { theme }) => {
|
||||
if (theme.colors[c])
|
||||
return { color: theme.colors[c] }
|
||||
}],
|
||||
]
|
||||
```
|
||||
|
||||
## Using Theme in Variants
|
||||
|
||||
```ts
|
||||
variants: [
|
||||
{
|
||||
name: 'variant-name',
|
||||
match(matcher, { theme }) {
|
||||
// Access theme.breakpoints, theme.colors, etc.
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
## Using Theme in Shortcuts
|
||||
|
||||
```ts
|
||||
shortcuts: [
|
||||
[/^badge-(.*)$/, ([, c], { theme }) => {
|
||||
if (Object.keys(theme.colors).includes(c))
|
||||
return `bg-${c}4:10 text-${c}5 rounded`
|
||||
}],
|
||||
]
|
||||
```
|
||||
|
||||
## Breakpoints
|
||||
|
||||
**Warning:** Custom `breakpoints` object **overrides** the default, not merges.
|
||||
|
||||
```ts
|
||||
theme: {
|
||||
breakpoints: {
|
||||
sm: '320px',
|
||||
md: '640px',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Only `sm:` and `md:` variants will be available.
|
||||
|
||||
### Inherit Default Breakpoints
|
||||
|
||||
Use `extendTheme` to merge with defaults:
|
||||
|
||||
```ts
|
||||
extendTheme: (theme) => {
|
||||
return {
|
||||
...theme,
|
||||
breakpoints: {
|
||||
...theme.breakpoints,
|
||||
sm: '320px',
|
||||
md: '640px',
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** `verticalBreakpoints` works the same for vertical layout.
|
||||
|
||||
### Breakpoint Sorting
|
||||
|
||||
Breakpoints are sorted by size. Use consistent units to avoid errors:
|
||||
|
||||
```ts
|
||||
theme: {
|
||||
breakpoints: {
|
||||
sm: '320px',
|
||||
// Don't mix units - convert rem to px
|
||||
// md: '40rem', // Bad
|
||||
md: `${40 * 16}px`, // Good
|
||||
lg: '960px',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## ExtendTheme
|
||||
|
||||
`extendTheme` lets you modify the merged theme object:
|
||||
|
||||
### Mutate Theme
|
||||
|
||||
```ts
|
||||
extendTheme: (theme) => {
|
||||
theme.colors.veryCool = '#0000ff'
|
||||
theme.colors.brand = {
|
||||
primary: 'hsl(var(--hue, 217) 78% 51%)',
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Replace Theme
|
||||
|
||||
Return a new object to completely replace:
|
||||
|
||||
```ts
|
||||
extendTheme: (theme) => {
|
||||
return {
|
||||
...theme,
|
||||
colors: {
|
||||
...theme.colors,
|
||||
veryCool: '#0000ff',
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Theme Differences in Presets
|
||||
|
||||
### preset-wind3 vs preset-wind4
|
||||
|
||||
| preset-wind3 | preset-wind4 |
|
||||
|--------------|--------------|
|
||||
| `fontFamily` | `font` |
|
||||
| `fontSize` | `text.fontSize` |
|
||||
| `lineHeight` | `text.lineHeight` or `leading` |
|
||||
| `letterSpacing` | `text.letterSpacing` or `tracking` |
|
||||
| `borderRadius` | `radius` |
|
||||
| `easing` | `ease` |
|
||||
| `breakpoints` | `breakpoint` |
|
||||
| `boxShadow` | `shadow` |
|
||||
| `transitionProperty` | `property` |
|
||||
|
||||
## Common Theme Keys
|
||||
|
||||
- `colors` - Color palette
|
||||
- `breakpoints` - Responsive breakpoints
|
||||
- `fontFamily` - Font stacks
|
||||
- `fontSize` - Text sizes
|
||||
- `spacing` - Spacing scale
|
||||
- `borderRadius` - Border radius values
|
||||
- `boxShadow` - Shadow definitions
|
||||
- `animation` - Animation keyframes and timing
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/config/theme
|
||||
-->
|
||||
175
.claude/skills/unocss/references/core-variants.md
Normal file
175
.claude/skills/unocss/references/core-variants.md
Normal file
@@ -0,0 +1,175 @@
|
||||
---
|
||||
name: unocss-variants
|
||||
description: Apply variations like hover:, dark:, responsive to rules
|
||||
---
|
||||
|
||||
# UnoCSS Variants
|
||||
|
||||
Variants apply modifications to utility rules, like `hover:`, `dark:`, or responsive prefixes.
|
||||
|
||||
## How Variants Work
|
||||
|
||||
When matching `hover:m-2`:
|
||||
|
||||
1. `hover:m-2` is extracted from source
|
||||
2. Sent to all variants for matching
|
||||
3. `hover:` variant matches and returns `m-2`
|
||||
4. Result `m-2` continues to next variants
|
||||
5. Finally matches the rule `.m-2 { margin: 0.5rem; }`
|
||||
6. Variant transformation applied: `.hover\:m-2:hover { margin: 0.5rem; }`
|
||||
|
||||
## Creating Custom Variants
|
||||
|
||||
```ts
|
||||
variants: [
|
||||
// hover: variant
|
||||
(matcher) => {
|
||||
if (!matcher.startsWith('hover:'))
|
||||
return matcher
|
||||
return {
|
||||
// Remove prefix, pass to next variants/rules
|
||||
matcher: matcher.slice(6),
|
||||
// Modify the selector
|
||||
selector: s => `${s}:hover`,
|
||||
}
|
||||
},
|
||||
],
|
||||
rules: [
|
||||
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
|
||||
]
|
||||
```
|
||||
|
||||
## Variant Return Object
|
||||
|
||||
- `matcher` - The processed class name to pass forward
|
||||
- `selector` - Function to customize the CSS selector
|
||||
- `parent` - Wrapper like `@media`, `@supports`
|
||||
- `layer` - Specify output layer
|
||||
- `sort` - Control ordering
|
||||
|
||||
## Built-in Variants (preset-wind3)
|
||||
|
||||
### Pseudo-classes
|
||||
- `hover:`, `focus:`, `active:`, `visited:`
|
||||
- `first:`, `last:`, `odd:`, `even:`
|
||||
- `disabled:`, `checked:`, `required:`
|
||||
- `focus-within:`, `focus-visible:`
|
||||
|
||||
### Pseudo-elements
|
||||
- `before:`, `after:`
|
||||
- `placeholder:`, `selection:`
|
||||
- `marker:`, `file:`
|
||||
|
||||
### Responsive
|
||||
- `sm:`, `md:`, `lg:`, `xl:`, `2xl:`
|
||||
- `lt-sm:` (less than sm)
|
||||
- `at-lg:` (at lg only)
|
||||
|
||||
### Dark Mode
|
||||
- `dark:` - Class-based dark mode (default)
|
||||
- `@dark:` - Media query dark mode
|
||||
|
||||
### Group/Peer
|
||||
- `group-hover:`, `group-focus:`
|
||||
- `peer-checked:`, `peer-focus:`
|
||||
|
||||
### Container Queries
|
||||
- `@container`, `@sm:`, `@md:`
|
||||
|
||||
### Print
|
||||
- `print:`
|
||||
|
||||
### Supports
|
||||
- `supports-[display:grid]:`
|
||||
|
||||
### Aria
|
||||
- `aria-checked:`, `aria-disabled:`
|
||||
|
||||
### Data Attributes
|
||||
- `data-[state=open]:`
|
||||
|
||||
## Dark Mode Configuration
|
||||
|
||||
### Class-based (default)
|
||||
```ts
|
||||
presetWind3({
|
||||
dark: 'class'
|
||||
})
|
||||
```
|
||||
|
||||
```html
|
||||
<div class="dark:bg-gray-800">
|
||||
```
|
||||
|
||||
Generates: `.dark .dark\:bg-gray-800 { ... }`
|
||||
|
||||
### Media Query
|
||||
```ts
|
||||
presetWind3({
|
||||
dark: 'media'
|
||||
})
|
||||
```
|
||||
|
||||
Generates: `@media (prefers-color-scheme: dark) { ... }`
|
||||
|
||||
### Opt-in Media Query
|
||||
Use `@dark:` regardless of config:
|
||||
|
||||
```html
|
||||
<div class="@dark:bg-gray-800">
|
||||
```
|
||||
|
||||
### Custom Selectors
|
||||
```ts
|
||||
presetWind3({
|
||||
dark: {
|
||||
light: '.light-mode',
|
||||
dark: '.dark-mode',
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## CSS @layer Variant
|
||||
|
||||
Native CSS `@layer` support:
|
||||
|
||||
```html
|
||||
<div class="layer-foo:p-4" />
|
||||
```
|
||||
|
||||
Generates:
|
||||
```css
|
||||
@layer foo {
|
||||
.layer-foo\:p-4 { padding: 1rem; }
|
||||
}
|
||||
```
|
||||
|
||||
## Breakpoint Differences from Windi CSS
|
||||
|
||||
| Windi CSS | UnoCSS |
|
||||
|-----------|--------|
|
||||
| `<sm:p-1` | `lt-sm:p-1` |
|
||||
| `@lg:p-1` | `at-lg:p-1` |
|
||||
| `>xl:p-1` | `xl:p-1` |
|
||||
|
||||
## Media Hover (Experimental)
|
||||
|
||||
Addresses sticky hover on touch devices:
|
||||
|
||||
```html
|
||||
<div class="@hover-text-red">
|
||||
```
|
||||
|
||||
Generates:
|
||||
```css
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.\@hover-text-red:hover { color: rgb(248 113 113); }
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/config/variants
|
||||
- https://unocss.dev/presets/wind3
|
||||
- https://unocss.dev/presets/mini
|
||||
-->
|
||||
199
.claude/skills/unocss/references/integrations-nuxt.md
Normal file
199
.claude/skills/unocss/references/integrations-nuxt.md
Normal file
@@ -0,0 +1,199 @@
|
||||
---
|
||||
name: unocss-nuxt-integration
|
||||
description: UnoCSS module for Nuxt applications
|
||||
---
|
||||
|
||||
# UnoCSS Nuxt Integration
|
||||
|
||||
The official Nuxt module for UnoCSS.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pnpm add -D unocss @unocss/nuxt
|
||||
```
|
||||
|
||||
Add to Nuxt config:
|
||||
|
||||
```ts
|
||||
// nuxt.config.ts
|
||||
export default defineNuxtConfig({
|
||||
modules: [
|
||||
'@unocss/nuxt',
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
Create config file:
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import { defineConfig, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** The `uno.css` entry is automatically injected by the module.
|
||||
|
||||
## Support Status
|
||||
|
||||
| Build Tool | Nuxt 2 | Nuxt Bridge | Nuxt 3 |
|
||||
|------------|--------|-------------|--------|
|
||||
| Webpack Dev | ✅ | ✅ | 🚧 |
|
||||
| Webpack Build | ✅ | ✅ | ✅ |
|
||||
| Vite Dev | - | ✅ | ✅ |
|
||||
| Vite Build | - | ✅ | ✅ |
|
||||
|
||||
## Configuration
|
||||
|
||||
### Using uno.config.ts (Recommended)
|
||||
|
||||
Use a dedicated config file for best IDE support:
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import { defineConfig, presetWind3, presetIcons } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetIcons(),
|
||||
],
|
||||
shortcuts: {
|
||||
'btn': 'py-2 px-4 font-semibold rounded-lg',
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Nuxt Layers Support
|
||||
|
||||
Enable automatic config merging from Nuxt layers:
|
||||
|
||||
```ts
|
||||
// nuxt.config.ts
|
||||
export default defineNuxtConfig({
|
||||
unocss: {
|
||||
nuxtLayers: true,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Then in your root config:
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import config from './.nuxt/uno.config.mjs'
|
||||
|
||||
export default config
|
||||
```
|
||||
|
||||
Or extend the merged config:
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import { mergeConfigs } from '@unocss/core'
|
||||
import config from './.nuxt/uno.config.mjs'
|
||||
|
||||
export default mergeConfigs([config, {
|
||||
// Your overrides
|
||||
shortcuts: {
|
||||
'custom': 'text-red-500',
|
||||
},
|
||||
}])
|
||||
```
|
||||
|
||||
## Common Setup Example
|
||||
|
||||
```ts
|
||||
// nuxt.config.ts
|
||||
export default defineNuxtConfig({
|
||||
modules: [
|
||||
'@unocss/nuxt',
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import {
|
||||
defineConfig,
|
||||
presetAttributify,
|
||||
presetIcons,
|
||||
presetTypography,
|
||||
presetWebFonts,
|
||||
presetWind3,
|
||||
transformerDirectives,
|
||||
transformerVariantGroup,
|
||||
} from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetAttributify(),
|
||||
presetIcons({
|
||||
scale: 1.2,
|
||||
}),
|
||||
presetTypography(),
|
||||
presetWebFonts({
|
||||
fonts: {
|
||||
sans: 'DM Sans',
|
||||
mono: 'DM Mono',
|
||||
},
|
||||
}),
|
||||
],
|
||||
transformers: [
|
||||
transformerDirectives(),
|
||||
transformerVariantGroup(),
|
||||
],
|
||||
shortcuts: [
|
||||
['btn', 'px-4 py-1 rounded inline-block bg-teal-600 text-white cursor-pointer hover:bg-teal-700 disabled:cursor-default disabled:bg-gray-600 disabled:opacity-50'],
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Usage in Components
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="p-4 text-center">
|
||||
<h1 class="text-3xl font-bold text-blue-600">
|
||||
Hello UnoCSS!
|
||||
</h1>
|
||||
<button class="btn mt-4">
|
||||
Click me
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
With attributify mode:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div p="4" text="center">
|
||||
<h1 text="3xl blue-600" font="bold">
|
||||
Hello UnoCSS!
|
||||
</h1>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Inspector
|
||||
|
||||
In development, visit `/_nuxt/__unocss` to access the UnoCSS inspector.
|
||||
|
||||
## Key Differences from Vite
|
||||
|
||||
- No need to import `virtual:uno.css` - automatically injected
|
||||
- Config file discovery works the same
|
||||
- All Vite plugin features available
|
||||
- Nuxt layers config merging available
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/integrations/nuxt
|
||||
-->
|
||||
283
.claude/skills/unocss/references/integrations-vite.md
Normal file
283
.claude/skills/unocss/references/integrations-vite.md
Normal file
@@ -0,0 +1,283 @@
|
||||
---
|
||||
name: unocss-vite-integration
|
||||
description: Setting up UnoCSS with Vite and framework-specific tips
|
||||
---
|
||||
|
||||
# UnoCSS Vite Integration
|
||||
|
||||
The Vite plugin is the most common way to use UnoCSS.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pnpm add -D unocss
|
||||
```
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import UnoCSS from 'unocss/vite'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
UnoCSS(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
Create config file:
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import { defineConfig, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
Add to entry:
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
import 'virtual:uno.css'
|
||||
```
|
||||
|
||||
## Modes
|
||||
|
||||
### global (default)
|
||||
|
||||
Standard mode - generates global CSS injected via `uno.css` import.
|
||||
|
||||
```ts
|
||||
import 'virtual:uno.css'
|
||||
```
|
||||
|
||||
### vue-scoped
|
||||
|
||||
Injects generated CSS into Vue SFC `<style scoped>`.
|
||||
|
||||
```ts
|
||||
UnoCSS({
|
||||
mode: 'vue-scoped',
|
||||
})
|
||||
```
|
||||
|
||||
### shadow-dom
|
||||
|
||||
For Web Components using Shadow DOM:
|
||||
|
||||
```ts
|
||||
UnoCSS({
|
||||
mode: 'shadow-dom',
|
||||
})
|
||||
```
|
||||
|
||||
Add placeholder in component styles:
|
||||
|
||||
```ts
|
||||
const template = document.createElement('template')
|
||||
template.innerHTML = `
|
||||
<style>
|
||||
:host { ... }
|
||||
@unocss-placeholder
|
||||
</style>
|
||||
<div class="m-1em">...</div>
|
||||
`
|
||||
```
|
||||
|
||||
### per-module (experimental)
|
||||
|
||||
Generates CSS per module with optional scoping.
|
||||
|
||||
### dist-chunk (experimental)
|
||||
|
||||
Generates CSS per chunk on build for MPA.
|
||||
|
||||
## DevTools Support
|
||||
|
||||
Edit classes directly in browser DevTools:
|
||||
|
||||
```ts
|
||||
import 'virtual:uno.css'
|
||||
import 'virtual:unocss-devtools'
|
||||
```
|
||||
|
||||
**Warning:** Uses MutationObserver to detect changes. Dynamic classes from scripts will also be included.
|
||||
|
||||
## Framework-Specific Setup
|
||||
|
||||
### React
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import React from '@vitejs/plugin-react'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS(), // Must be before React when using attributify
|
||||
React(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Remove `tsc` from build script if using `@unocss/preset-attributify`.
|
||||
|
||||
### Vue
|
||||
|
||||
Works out of the box with `@vitejs/plugin-vue`.
|
||||
|
||||
### Svelte
|
||||
|
||||
```ts
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte'
|
||||
import extractorSvelte from '@unocss/extractor-svelte'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS({
|
||||
extractors: [extractorSvelte()],
|
||||
}),
|
||||
svelte(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
Supports `class:foo` and `class:foo={bar}` syntax.
|
||||
|
||||
### SvelteKit
|
||||
|
||||
Same as Svelte, use `sveltekit()` from `@sveltejs/kit/vite`.
|
||||
|
||||
### Solid
|
||||
|
||||
```ts
|
||||
import UnoCSS from 'unocss/vite'
|
||||
import solidPlugin from 'vite-plugin-solid'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS(),
|
||||
solidPlugin(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Preact
|
||||
|
||||
```ts
|
||||
import Preact from '@preact/preset-vite'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS(),
|
||||
Preact(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Elm
|
||||
|
||||
```ts
|
||||
import Elm from 'vite-plugin-elm'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
Elm(),
|
||||
UnoCSS(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Web Components (Lit)
|
||||
|
||||
```ts
|
||||
UnoCSS({
|
||||
mode: 'shadow-dom',
|
||||
shortcuts: [
|
||||
{ 'cool-blue': 'bg-blue-500 text-white' },
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
// my-element.ts
|
||||
@customElement('my-element')
|
||||
export class MyElement extends LitElement {
|
||||
static styles = css`
|
||||
:host { ... }
|
||||
@unocss-placeholder
|
||||
`
|
||||
}
|
||||
```
|
||||
|
||||
Supports `part-[<part-name>]:<utility>` for `::part` styling.
|
||||
|
||||
## Inspector
|
||||
|
||||
Visit `http://localhost:5173/__unocss` in dev mode to:
|
||||
|
||||
- Inspect generated CSS rules
|
||||
- See applied classes per file
|
||||
- Test utilities in REPL
|
||||
|
||||
## Legacy Browser Support
|
||||
|
||||
With `@vitejs/plugin-legacy`:
|
||||
|
||||
```ts
|
||||
import legacy from '@vitejs/plugin-legacy'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS({
|
||||
legacy: {
|
||||
renderModernChunks: false,
|
||||
},
|
||||
}),
|
||||
legacy({
|
||||
targets: ['defaults', 'not IE 11'],
|
||||
renderModernChunks: false,
|
||||
}),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## VanillaJS / TypeScript
|
||||
|
||||
By default, `.js` and `.ts` files are not extracted. Configure to include:
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
export default defineConfig({
|
||||
content: {
|
||||
pipeline: {
|
||||
include: [
|
||||
/\.(vue|svelte|[jt]sx|html)($|\?)/,
|
||||
'src/**/*.{js,ts}',
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Or use magic comment in files:
|
||||
|
||||
```ts
|
||||
// @unocss-include
|
||||
export const classes = {
|
||||
active: 'bg-primary text-white',
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/integrations/vite
|
||||
-->
|
||||
142
.claude/skills/unocss/references/preset-attributify.md
Normal file
142
.claude/skills/unocss/references/preset-attributify.md
Normal file
@@ -0,0 +1,142 @@
|
||||
---
|
||||
name: preset-attributify
|
||||
description: Group utilities in HTML attributes instead of class
|
||||
---
|
||||
|
||||
# Preset Attributify
|
||||
|
||||
Group utilities in HTML attributes for better readability.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetAttributify, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetAttributify(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
Instead of long class strings:
|
||||
|
||||
```html
|
||||
<button class="bg-blue-400 hover:bg-blue-500 text-sm text-white font-mono font-light py-2 px-4 rounded border-2 border-blue-200">
|
||||
Button
|
||||
</button>
|
||||
```
|
||||
|
||||
Group by prefix in attributes:
|
||||
|
||||
```html
|
||||
<button
|
||||
bg="blue-400 hover:blue-500"
|
||||
text="sm white"
|
||||
font="mono light"
|
||||
p="y-2 x-4"
|
||||
border="2 rounded blue-200"
|
||||
>
|
||||
Button
|
||||
</button>
|
||||
```
|
||||
|
||||
## Prefix Self-Referencing
|
||||
|
||||
For utilities matching their prefix (`flex`, `grid`, `border`), use `~`:
|
||||
|
||||
```html
|
||||
<!-- Before -->
|
||||
<button class="border border-red">Button</button>
|
||||
|
||||
<!-- After -->
|
||||
<button border="~ red">Button</button>
|
||||
```
|
||||
|
||||
## Valueless Attributify
|
||||
|
||||
Use utilities as boolean attributes:
|
||||
|
||||
```html
|
||||
<div m-2 rounded text-teal-400 />
|
||||
```
|
||||
|
||||
## Handling Property Conflicts
|
||||
|
||||
When attribute names conflict with HTML properties:
|
||||
|
||||
```html
|
||||
<!-- Use un- prefix -->
|
||||
<a un-text="red">Text color to red</a>
|
||||
```
|
||||
|
||||
### Enforce Prefix
|
||||
|
||||
```ts
|
||||
presetAttributify({
|
||||
prefix: 'un-',
|
||||
prefixedOnly: true,
|
||||
})
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetAttributify({
|
||||
strict: false, // Only generate CSS for attributify
|
||||
prefix: 'un-', // Attribute prefix
|
||||
prefixedOnly: false, // Require prefix for all
|
||||
nonValuedAttribute: true, // Support valueless attributes
|
||||
ignoreAttributes: [], // Attributes to ignore
|
||||
trueToNonValued: false, // Treat value="true" as valueless
|
||||
})
|
||||
```
|
||||
|
||||
## TypeScript Support
|
||||
|
||||
### Vue 3
|
||||
|
||||
```ts
|
||||
// html.d.ts
|
||||
declare module '@vue/runtime-dom' {
|
||||
interface HTMLAttributes { [key: string]: any }
|
||||
}
|
||||
declare module '@vue/runtime-core' {
|
||||
interface AllowedComponentProps { [key: string]: any }
|
||||
}
|
||||
export {}
|
||||
```
|
||||
|
||||
### React
|
||||
|
||||
```ts
|
||||
import type { AttributifyAttributes } from '@unocss/preset-attributify'
|
||||
|
||||
declare module 'react' {
|
||||
interface HTMLAttributes<T> extends AttributifyAttributes {}
|
||||
}
|
||||
```
|
||||
|
||||
## JSX Support
|
||||
|
||||
For JSX where `<div foo>` becomes `<div foo={true}>`:
|
||||
|
||||
```ts
|
||||
import { transformerAttributifyJsx } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
transformers: [
|
||||
transformerAttributifyJsx(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
**Important:** Only use attributify if `uno.config.*` shows `presetAttributify()` is enabled.
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/attributify
|
||||
-->
|
||||
184
.claude/skills/unocss/references/preset-icons.md
Normal file
184
.claude/skills/unocss/references/preset-icons.md
Normal file
@@ -0,0 +1,184 @@
|
||||
---
|
||||
name: preset-icons
|
||||
description: Pure CSS icons using Iconify with any icon set
|
||||
---
|
||||
|
||||
# Preset Icons
|
||||
|
||||
Use any icon as a pure CSS class, powered by Iconify.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pnpm add -D @unocss/preset-icons @iconify-json/[collection-name]
|
||||
```
|
||||
|
||||
Example: `@iconify-json/mdi` for Material Design Icons, `@iconify-json/carbon` for Carbon icons.
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetIcons } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetIcons(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Two naming conventions:
|
||||
- `<prefix><collection>-<icon>` → `i-ph-anchor-simple-thin`
|
||||
- `<prefix><collection>:<icon>` → `i-ph:anchor-simple-thin`
|
||||
|
||||
```html
|
||||
<!-- Phosphor anchor icon -->
|
||||
<div class="i-ph-anchor-simple-thin" />
|
||||
|
||||
<!-- Material Design alarm with color -->
|
||||
<div class="i-mdi-alarm text-orange-400" />
|
||||
|
||||
<!-- Large Vue logo -->
|
||||
<div class="i-logos-vue text-3xl" />
|
||||
|
||||
<!-- Dynamic: Sun in light mode, Moon in dark -->
|
||||
<button class="i-carbon-sun dark:i-carbon-moon" />
|
||||
|
||||
<!-- Hover effect -->
|
||||
<div class="i-twemoji-grinning-face-with-smiling-eyes hover:i-twemoji-face-with-tears-of-joy" />
|
||||
```
|
||||
|
||||
Browse icons at [icones.js.org](https://icones.js.org/) or [Iconify](https://icon-sets.iconify.design/).
|
||||
|
||||
## Icon Modes
|
||||
|
||||
Icons automatically choose between `mask` (monochrome) and `background-img` (colorful).
|
||||
|
||||
### Force Specific Mode
|
||||
|
||||
- `?mask` - Render as mask (colorable with `currentColor`)
|
||||
- `?bg` - Render as background image (preserves original colors)
|
||||
|
||||
```html
|
||||
<!-- Original with colors -->
|
||||
<div class="i-vscode-icons:file-type-light-pnpm" />
|
||||
|
||||
<!-- Force mask mode, apply custom color -->
|
||||
<div class="i-vscode-icons:file-type-light-pnpm?mask text-red-300" />
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetIcons({
|
||||
scale: 1.2, // Scale relative to font size
|
||||
prefix: 'i-', // Class prefix (default)
|
||||
mode: 'auto', // 'auto' | 'mask' | 'bg'
|
||||
extraProperties: {
|
||||
'display': 'inline-block',
|
||||
'vertical-align': 'middle',
|
||||
},
|
||||
warn: true, // Warn on missing icons
|
||||
autoInstall: true, // Auto-install missing icon sets
|
||||
cdn: 'https://esm.sh/', // CDN for browser usage
|
||||
})
|
||||
```
|
||||
|
||||
## Custom Icon Collections
|
||||
|
||||
### Inline SVGs
|
||||
|
||||
```ts
|
||||
presetIcons({
|
||||
collections: {
|
||||
custom: {
|
||||
circle: '<svg viewBox="0 0 120 120"><circle cx="60" cy="60" r="50"></circle></svg>',
|
||||
},
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Usage: `<span class="i-custom:circle"></span>`
|
||||
|
||||
### File System Loader
|
||||
|
||||
```ts
|
||||
import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'
|
||||
|
||||
presetIcons({
|
||||
collections: {
|
||||
'my-icons': FileSystemIconLoader(
|
||||
'./assets/icons',
|
||||
svg => svg.replace(/#fff/, 'currentColor')
|
||||
),
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Dynamic Import (Browser)
|
||||
|
||||
```ts
|
||||
import presetIcons from '@unocss/preset-icons/browser'
|
||||
|
||||
presetIcons({
|
||||
collections: {
|
||||
carbon: () => import('@iconify-json/carbon/icons.json').then(i => i.default),
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Icon Customization
|
||||
|
||||
```ts
|
||||
presetIcons({
|
||||
customizations: {
|
||||
// Transform SVG
|
||||
transform(svg, collection, icon) {
|
||||
return svg.replace(/#fff/, 'currentColor')
|
||||
},
|
||||
// Global sizing
|
||||
customize(props) {
|
||||
props.width = '2em'
|
||||
props.height = '2em'
|
||||
return props
|
||||
},
|
||||
// Per-collection
|
||||
iconCustomizer(collection, icon, props) {
|
||||
if (collection === 'mdi') {
|
||||
props.width = '2em'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## CSS Directive
|
||||
|
||||
Use `icon()` in CSS (requires transformer-directives):
|
||||
|
||||
```css
|
||||
.icon {
|
||||
background-image: icon('i-carbon-sun');
|
||||
}
|
||||
.icon-colored {
|
||||
background-image: icon('i-carbon-moon', '#fff');
|
||||
}
|
||||
```
|
||||
|
||||
## Accessibility
|
||||
|
||||
```html
|
||||
<!-- With label -->
|
||||
<a href="/profile" aria-label="Profile" class="i-ph:user-duotone"></a>
|
||||
|
||||
<!-- Decorative -->
|
||||
<a href="/profile">
|
||||
<span aria-hidden="true" class="i-ph:user-duotone"></span>
|
||||
My Profile
|
||||
</a>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/icons
|
||||
-->
|
||||
158
.claude/skills/unocss/references/preset-mini.md
Normal file
158
.claude/skills/unocss/references/preset-mini.md
Normal file
@@ -0,0 +1,158 @@
|
||||
---
|
||||
name: preset-mini
|
||||
description: Minimal preset with essential utilities for UnoCSS
|
||||
---
|
||||
|
||||
# Preset Mini
|
||||
|
||||
The minimal preset with only essential rules and variants. Good starting point for custom presets.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetMini } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetMini(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## What's Included
|
||||
|
||||
Subset of `preset-wind3` with essential utilities aligned to CSS properties:
|
||||
|
||||
- Basic spacing (margin, padding)
|
||||
- Display (flex, grid, block, etc.)
|
||||
- Positioning (absolute, relative, fixed)
|
||||
- Sizing (width, height)
|
||||
- Colors (text, background, border)
|
||||
- Typography basics (font-size, font-weight)
|
||||
- Borders and border-radius
|
||||
- Basic transforms and transitions
|
||||
|
||||
## What's NOT Included
|
||||
|
||||
Opinionated or complex Tailwind utilities:
|
||||
- `container`
|
||||
- Complex animations
|
||||
- Gradients
|
||||
- Advanced typography
|
||||
- Prose classes
|
||||
|
||||
## Use Cases
|
||||
|
||||
1. **Building custom presets** - Start with mini and add only what you need
|
||||
2. **Minimal bundle size** - When you only need basic utilities
|
||||
3. **Learning** - Understand UnoCSS core without Tailwind complexity
|
||||
|
||||
## Dark Mode
|
||||
|
||||
Same as preset-wind3:
|
||||
|
||||
```ts
|
||||
presetMini({
|
||||
dark: 'class' // or 'media'
|
||||
})
|
||||
```
|
||||
|
||||
```html
|
||||
<div class="dark:bg-red:10" />
|
||||
```
|
||||
|
||||
Class-based:
|
||||
```css
|
||||
.dark .dark\:bg-red\:10 {
|
||||
background-color: rgb(248 113 113 / 0.1);
|
||||
}
|
||||
```
|
||||
|
||||
Media query:
|
||||
```css
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.dark\:bg-red\:10 {
|
||||
background-color: rgb(248 113 113 / 0.1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## CSS @layer Variant
|
||||
|
||||
Native CSS layer support:
|
||||
|
||||
```html
|
||||
<div class="layer-foo:p4" />
|
||||
```
|
||||
|
||||
```css
|
||||
@layer foo {
|
||||
.layer-foo\:p4 {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Theme Customization
|
||||
|
||||
```ts
|
||||
presetMini({
|
||||
theme: {
|
||||
colors: {
|
||||
veryCool: '#0000ff',
|
||||
brand: {
|
||||
primary: 'hsl(var(--hue, 217) 78% 51%)',
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** `breakpoints` property is overridden, not merged.
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetMini({
|
||||
// Dark mode: 'class' | 'media' | { light: string, dark: string }
|
||||
dark: 'class',
|
||||
|
||||
// Generate [group=""] instead of .group for attributify
|
||||
attributifyPseudo: false,
|
||||
|
||||
// CSS variable prefix (default: 'un-')
|
||||
variablePrefix: 'un-',
|
||||
|
||||
// Utility prefix
|
||||
prefix: undefined,
|
||||
|
||||
// Preflight generation: true | false | 'on-demand'
|
||||
preflight: true,
|
||||
})
|
||||
```
|
||||
|
||||
## Building on Mini
|
||||
|
||||
Create custom preset extending mini:
|
||||
|
||||
```ts
|
||||
import { presetMini } from 'unocss'
|
||||
import type { Preset } from 'unocss'
|
||||
|
||||
export const myPreset: Preset = {
|
||||
name: 'my-preset',
|
||||
presets: [presetMini()],
|
||||
rules: [
|
||||
// Add custom rules
|
||||
['card', { 'border-radius': '8px', 'box-shadow': '0 2px 8px rgba(0,0,0,0.1)' }],
|
||||
],
|
||||
shortcuts: {
|
||||
'btn': 'px-4 py-2 rounded bg-blue-500 text-white',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/mini
|
||||
-->
|
||||
97
.claude/skills/unocss/references/preset-rem-to-px.md
Normal file
97
.claude/skills/unocss/references/preset-rem-to-px.md
Normal file
@@ -0,0 +1,97 @@
|
||||
---
|
||||
name: preset-rem-to-px
|
||||
description: Convert rem units to px for utilities
|
||||
---
|
||||
|
||||
# Preset Rem to Px
|
||||
|
||||
Converts `rem` units to `px` in generated utilities.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetRemToPx, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetRemToPx(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## What It Does
|
||||
|
||||
Transforms all rem values to px:
|
||||
|
||||
```html
|
||||
<div class="p-4">
|
||||
```
|
||||
|
||||
Without preset:
|
||||
```css
|
||||
.p-4 { padding: 1rem; }
|
||||
```
|
||||
|
||||
With preset:
|
||||
```css
|
||||
.p-4 { padding: 16px; }
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
- Projects requiring pixel-perfect designs
|
||||
- Environments where rem doesn't work well
|
||||
- Consistency with pixel-based design systems
|
||||
- Email templates (better compatibility)
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetRemToPx({
|
||||
// Base font size for conversion (default: 16)
|
||||
baseFontSize: 16,
|
||||
})
|
||||
```
|
||||
|
||||
Custom base:
|
||||
|
||||
```ts
|
||||
presetRemToPx({
|
||||
baseFontSize: 14, // 1rem = 14px
|
||||
})
|
||||
```
|
||||
|
||||
## With Preset Wind4
|
||||
|
||||
**Note:** `presetRemToPx` is not needed with `preset-wind4`. Use the built-in processor instead:
|
||||
|
||||
```ts
|
||||
import { createRemToPxProcessor } from '@unocss/preset-wind4/utils'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind4({
|
||||
preflights: {
|
||||
theme: {
|
||||
process: createRemToPxProcessor(),
|
||||
}
|
||||
},
|
||||
}),
|
||||
],
|
||||
// Also apply to utilities
|
||||
postprocess: [createRemToPxProcessor()],
|
||||
})
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Order matters: place after the preset that generates rem values
|
||||
- Affects all utilities with rem units
|
||||
- Theme values in rem are also converted
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/rem-to-px
|
||||
- https://unocss.dev/presets/wind4
|
||||
-->
|
||||
134
.claude/skills/unocss/references/preset-tagify.md
Normal file
134
.claude/skills/unocss/references/preset-tagify.md
Normal file
@@ -0,0 +1,134 @@
|
||||
---
|
||||
name: preset-tagify
|
||||
description: Use utilities as HTML tag names
|
||||
---
|
||||
|
||||
# Preset Tagify
|
||||
|
||||
Use CSS utilities directly as HTML tag names.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetTagify } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetTagify(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
Instead of:
|
||||
|
||||
```html
|
||||
<span class="text-red">red text</span>
|
||||
<div class="flex">flexbox</div>
|
||||
<span class="i-line-md-emoji-grin"></span>
|
||||
```
|
||||
|
||||
Use tag names directly:
|
||||
|
||||
```html
|
||||
<text-red>red text</text-red>
|
||||
<flex>flexbox</flex>
|
||||
<i-line-md-emoji-grin />
|
||||
```
|
||||
|
||||
Works exactly the same!
|
||||
|
||||
## With Prefix
|
||||
|
||||
```ts
|
||||
presetTagify({
|
||||
prefix: 'un-'
|
||||
})
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- Matched -->
|
||||
<un-flex></un-flex>
|
||||
|
||||
<!-- Not matched -->
|
||||
<flex></flex>
|
||||
```
|
||||
|
||||
## Extra Properties
|
||||
|
||||
Add CSS properties to matched tags:
|
||||
|
||||
```ts
|
||||
presetTagify({
|
||||
// Add display: inline-block to icons
|
||||
extraProperties: matched => matched.startsWith('i-')
|
||||
? { display: 'inline-block' }
|
||||
: {},
|
||||
})
|
||||
```
|
||||
|
||||
Or apply to all:
|
||||
|
||||
```ts
|
||||
presetTagify({
|
||||
extraProperties: { display: 'block' }
|
||||
})
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetTagify({
|
||||
// Tag prefix
|
||||
prefix: '',
|
||||
|
||||
// Excluded tags (won't be processed)
|
||||
excludedTags: ['b', /^h\d+$/, 'table'],
|
||||
|
||||
// Extra CSS properties
|
||||
extraProperties: {},
|
||||
|
||||
// Enable default extractor
|
||||
defaultExtractor: true,
|
||||
})
|
||||
```
|
||||
|
||||
## Excluded Tags
|
||||
|
||||
By default, these tags are excluded:
|
||||
- `b` (bold)
|
||||
- `h1` through `h6` (headings)
|
||||
- `table`
|
||||
|
||||
Add your own:
|
||||
|
||||
```ts
|
||||
presetTagify({
|
||||
excludedTags: [
|
||||
'b',
|
||||
/^h\d+$/,
|
||||
'table',
|
||||
'article', // Add custom exclusions
|
||||
/^my-/, // Exclude tags starting with 'my-'
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
- Quick prototyping
|
||||
- Cleaner HTML for simple pages
|
||||
- Icon embedding: `<i-carbon-sun />`
|
||||
- Semantic-like styling: `<flex-center>`, `<text-red>`
|
||||
|
||||
## Limitations
|
||||
|
||||
- Custom element names must contain a hyphen (HTML spec)
|
||||
- Some frameworks may not support all custom elements
|
||||
- Utilities without hyphens need the prefix option
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/tagify
|
||||
-->
|
||||
95
.claude/skills/unocss/references/preset-typography.md
Normal file
95
.claude/skills/unocss/references/preset-typography.md
Normal file
@@ -0,0 +1,95 @@
|
||||
---
|
||||
name: preset-typography
|
||||
description: Prose classes for typographic defaults on vanilla HTML content
|
||||
---
|
||||
|
||||
# Preset Typography
|
||||
|
||||
Prose classes for adding typographic defaults to vanilla HTML content.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetTypography, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(), // Required!
|
||||
presetTypography(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```html
|
||||
<article class="prose">
|
||||
<h1>My Article</h1>
|
||||
<p>This is styled with typographic defaults...</p>
|
||||
</article>
|
||||
```
|
||||
|
||||
## Sizes
|
||||
|
||||
```html
|
||||
<article class="prose prose-sm">Small</article>
|
||||
<article class="prose prose-base">Base (default)</article>
|
||||
<article class="prose prose-lg">Large</article>
|
||||
<article class="prose prose-xl">Extra large</article>
|
||||
<article class="prose prose-2xl">2X large</article>
|
||||
```
|
||||
|
||||
Responsive:
|
||||
```html
|
||||
<article class="prose prose-sm md:prose-base lg:prose-lg">
|
||||
Responsive typography
|
||||
</article>
|
||||
```
|
||||
|
||||
## Colors
|
||||
|
||||
```html
|
||||
<article class="prose prose-gray">Gray (default)</article>
|
||||
<article class="prose prose-slate">Slate</article>
|
||||
<article class="prose prose-blue">Blue</article>
|
||||
```
|
||||
|
||||
## Dark Mode
|
||||
|
||||
```html
|
||||
<article class="prose dark:prose-invert">
|
||||
Dark mode typography
|
||||
</article>
|
||||
```
|
||||
|
||||
## Excluding Elements
|
||||
|
||||
```html
|
||||
<article class="prose">
|
||||
<p>Styled</p>
|
||||
<div class="not-prose">
|
||||
<p>NOT styled</p>
|
||||
</div>
|
||||
</article>
|
||||
```
|
||||
|
||||
**Note:** `not-prose` only works as a class.
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetTypography({
|
||||
selectorName: 'prose', // Custom selector
|
||||
cssVarPrefix: '--un-prose', // CSS variable prefix
|
||||
important: false, // Make !important
|
||||
cssExtend: {
|
||||
'code': { color: '#8b5cf6' },
|
||||
'a:hover': { color: '#f43f5e' },
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/typography
|
||||
-->
|
||||
91
.claude/skills/unocss/references/preset-web-fonts.md
Normal file
91
.claude/skills/unocss/references/preset-web-fonts.md
Normal file
@@ -0,0 +1,91 @@
|
||||
---
|
||||
name: preset-web-fonts
|
||||
description: Easy Google Fonts and other web fonts integration
|
||||
---
|
||||
|
||||
# Preset Web Fonts
|
||||
|
||||
Easily use web fonts from Google Fonts and other providers.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetWebFonts, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetWebFonts({
|
||||
provider: 'google',
|
||||
fonts: {
|
||||
sans: 'Roboto',
|
||||
mono: 'Fira Code',
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Providers
|
||||
|
||||
- `google` - Google Fonts (default)
|
||||
- `bunny` - Privacy-friendly alternative
|
||||
- `fontshare` - Quality fonts by ITF
|
||||
- `fontsource` - Self-hosted open source fonts
|
||||
- `coollabs` - Privacy-friendly drop-in replacement
|
||||
- `none` - Treat as system font
|
||||
|
||||
## Font Configuration
|
||||
|
||||
```ts
|
||||
fonts: {
|
||||
// Simple
|
||||
sans: 'Roboto',
|
||||
|
||||
// Multiple (fallback)
|
||||
mono: ['Fira Code', 'Fira Mono:400,700'],
|
||||
|
||||
// Detailed
|
||||
lato: [
|
||||
{
|
||||
name: 'Lato',
|
||||
weights: ['400', '700'],
|
||||
italic: true,
|
||||
},
|
||||
{
|
||||
name: 'sans-serif',
|
||||
provider: 'none',
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```html
|
||||
<p class="font-sans">Roboto</p>
|
||||
<code class="font-mono">Fira Code</code>
|
||||
```
|
||||
|
||||
## Local Fonts
|
||||
|
||||
Self-host fonts:
|
||||
|
||||
```ts
|
||||
import { createLocalFontProcessor } from '@unocss/preset-web-fonts/local'
|
||||
|
||||
presetWebFonts({
|
||||
provider: 'none',
|
||||
fonts: { sans: 'Roboto' },
|
||||
processors: createLocalFontProcessor({
|
||||
cacheDir: 'node_modules/.cache/unocss/fonts',
|
||||
fontAssetsDir: 'public/assets/fonts',
|
||||
fontServeBaseUrl: '/assets/fonts',
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/web-fonts
|
||||
-->
|
||||
194
.claude/skills/unocss/references/preset-wind3.md
Normal file
194
.claude/skills/unocss/references/preset-wind3.md
Normal file
@@ -0,0 +1,194 @@
|
||||
---
|
||||
name: preset-wind3
|
||||
description: Tailwind CSS / Windi CSS compatible preset for UnoCSS
|
||||
---
|
||||
|
||||
# Preset Wind3
|
||||
|
||||
The Tailwind CSS / Windi CSS compatible preset. Most commonly used preset for UnoCSS.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetWind3 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** `@unocss/preset-uno` and `@unocss/preset-wind` are deprecated and renamed to `@unocss/preset-wind3`.
|
||||
|
||||
## Features
|
||||
|
||||
- Full Tailwind CSS v3 compatibility
|
||||
- Dark mode (`dark:`, `@dark:`)
|
||||
- All responsive variants (`sm:`, `md:`, `lg:`, `xl:`, `2xl:`)
|
||||
- All standard utilities (flex, grid, spacing, colors, typography, etc.)
|
||||
- Animation support (includes Animate.css animations)
|
||||
|
||||
## Dark Mode
|
||||
|
||||
### Class-based (default)
|
||||
|
||||
```html
|
||||
<div class="dark:bg-gray-800">
|
||||
```
|
||||
|
||||
Generates: `.dark .dark\:bg-gray-800 { ... }`
|
||||
|
||||
### Media Query Based
|
||||
|
||||
```ts
|
||||
presetWind3({
|
||||
dark: 'media'
|
||||
})
|
||||
```
|
||||
|
||||
Generates: `@media (prefers-color-scheme: dark) { ... }`
|
||||
|
||||
### Opt-in Media Query
|
||||
|
||||
Use `@dark:` regardless of config:
|
||||
|
||||
```html
|
||||
<div class="@dark:bg-gray-800">
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetWind3({
|
||||
// Dark mode strategy
|
||||
dark: 'class', // 'class' | 'media' | { light: '.light', dark: '.dark' }
|
||||
|
||||
// Generate pseudo selector as [group=""] instead of .group
|
||||
attributifyPseudo: false,
|
||||
|
||||
// CSS custom properties prefix
|
||||
variablePrefix: 'un-',
|
||||
|
||||
// Utils prefix
|
||||
prefix: '',
|
||||
|
||||
// Generate preflight CSS
|
||||
preflight: true, // true | false | 'on-demand'
|
||||
|
||||
// Mark all utilities as !important
|
||||
important: false, // boolean | string (selector)
|
||||
})
|
||||
```
|
||||
|
||||
### Important Option
|
||||
|
||||
Make all utilities `!important`:
|
||||
|
||||
```ts
|
||||
presetWind3({
|
||||
important: true,
|
||||
})
|
||||
```
|
||||
|
||||
Or scope with selector to increase specificity without `!important`:
|
||||
|
||||
```ts
|
||||
presetWind3({
|
||||
important: '#app',
|
||||
})
|
||||
```
|
||||
|
||||
Output: `#app :is(.dark .dark\:bg-blue) { ... }`
|
||||
|
||||
## Differences from Tailwind CSS
|
||||
|
||||
### Quotes Not Supported
|
||||
|
||||
Template quotes don't work due to extractor:
|
||||
|
||||
```html
|
||||
<!-- Won't work -->
|
||||
<div class="before:content-['']">
|
||||
|
||||
<!-- Use shortcut instead -->
|
||||
<div class="before:content-empty">
|
||||
```
|
||||
|
||||
### Background Position
|
||||
|
||||
Use `position:` prefix for custom values:
|
||||
|
||||
```html
|
||||
<!-- Tailwind -->
|
||||
<div class="bg-[center_top_1rem]">
|
||||
|
||||
<!-- UnoCSS -->
|
||||
<div class="bg-[position:center_top_1rem]">
|
||||
```
|
||||
|
||||
### Animations
|
||||
|
||||
UnoCSS integrates Animate.css. Use `-alt` suffix for Animate.css versions when names conflict:
|
||||
|
||||
- `animate-bounce` - Tailwind version
|
||||
- `animate-bounce-alt` - Animate.css version
|
||||
|
||||
Custom animations:
|
||||
|
||||
```ts
|
||||
theme: {
|
||||
animation: {
|
||||
keyframes: {
|
||||
custom: '{0%, 100% { opacity: 0; } 50% { opacity: 1; }}',
|
||||
},
|
||||
durations: {
|
||||
custom: '1s',
|
||||
},
|
||||
timingFns: {
|
||||
custom: 'ease-in-out',
|
||||
},
|
||||
counts: {
|
||||
custom: 'infinite',
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Differences from Windi CSS
|
||||
|
||||
| Windi CSS | UnoCSS |
|
||||
|-----------|--------|
|
||||
| `<sm:p-1` | `lt-sm:p-1` |
|
||||
| `@lg:p-1` | `at-lg:p-1` |
|
||||
| `>xl:p-1` | `xl:p-1` |
|
||||
|
||||
Bracket syntax uses `_` instead of `,`:
|
||||
|
||||
```html
|
||||
<!-- Windi CSS -->
|
||||
<div class="grid-cols-[1fr,10px,max-content]">
|
||||
|
||||
<!-- UnoCSS -->
|
||||
<div class="grid-cols-[1fr_10px_max-content]">
|
||||
```
|
||||
|
||||
## Experimental: Media Hover
|
||||
|
||||
Addresses sticky hover on touch devices:
|
||||
|
||||
```html
|
||||
<div class="@hover-text-red">
|
||||
```
|
||||
|
||||
Generates:
|
||||
```css
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.\@hover-text-red:hover { ... }
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/wind3
|
||||
-->
|
||||
247
.claude/skills/unocss/references/preset-wind4.md
Normal file
247
.claude/skills/unocss/references/preset-wind4.md
Normal file
@@ -0,0 +1,247 @@
|
||||
---
|
||||
name: preset-wind4
|
||||
description: Tailwind CSS v4 compatible preset with enhanced features
|
||||
---
|
||||
|
||||
# Preset Wind4
|
||||
|
||||
The Tailwind CSS v4 compatible preset. Enhances preset-wind3 with modern CSS features.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, presetWind4 } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind4(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Key Differences from Wind3
|
||||
|
||||
### Built-in CSS Reset
|
||||
|
||||
No need for `@unocss/reset` - reset is built-in:
|
||||
|
||||
```ts
|
||||
// Remove these imports
|
||||
import '@unocss/reset/tailwind.css' // ❌ Not needed
|
||||
import '@unocss/reset/tailwind-compat.css' // ❌ Not needed
|
||||
|
||||
// Enable in config
|
||||
presetWind4({
|
||||
preflights: {
|
||||
reset: true,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### OKLCH Color Model
|
||||
|
||||
Uses `oklch` for better color perception and contrast. Not compatible with `presetLegacyCompat`.
|
||||
|
||||
### Theme CSS Variables
|
||||
|
||||
Automatically generates CSS variables from theme:
|
||||
|
||||
```css
|
||||
:root, :host {
|
||||
--spacing: 0.25rem;
|
||||
--font-sans: ui-sans-serif, system-ui, sans-serif;
|
||||
--colors-black: #000;
|
||||
--colors-white: #fff;
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
### @property CSS Rules
|
||||
|
||||
Uses `@property` for better browser optimization:
|
||||
|
||||
```css
|
||||
@property --un-text-opacity {
|
||||
syntax: '<percentage>';
|
||||
inherits: false;
|
||||
initial-value: 100%;
|
||||
}
|
||||
```
|
||||
|
||||
### Theme Key Changes
|
||||
|
||||
| preset-wind3 | preset-wind4 |
|
||||
|--------------|--------------|
|
||||
| `fontFamily` | `font` |
|
||||
| `fontSize` | `text.fontSize` |
|
||||
| `lineHeight` | `text.lineHeight` or `leading` |
|
||||
| `letterSpacing` | `text.letterSpacing` or `tracking` |
|
||||
| `borderRadius` | `radius` |
|
||||
| `easing` | `ease` |
|
||||
| `breakpoints` | `breakpoint` |
|
||||
| `verticalBreakpoints` | `verticalBreakpoint` |
|
||||
| `boxShadow` | `shadow` |
|
||||
| `transitionProperty` | `property` |
|
||||
| `container.maxWidth` | `containers.maxWidth` |
|
||||
| Size properties (`width`, `height`, etc.) | Unified to `spacing` |
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
presetWind4({
|
||||
preflights: {
|
||||
// Built-in reset styles
|
||||
reset: true,
|
||||
|
||||
// Theme CSS variables generation
|
||||
theme: 'on-demand', // true | false | 'on-demand'
|
||||
|
||||
// @property CSS rules
|
||||
property: true,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Theme Variable Processing
|
||||
|
||||
Convert rem to px for theme variables:
|
||||
|
||||
```ts
|
||||
import { createRemToPxProcessor } from '@unocss/preset-wind4/utils'
|
||||
|
||||
presetWind4({
|
||||
preflights: {
|
||||
theme: {
|
||||
mode: 'on-demand',
|
||||
process: createRemToPxProcessor(),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// Also apply to utilities
|
||||
export default defineConfig({
|
||||
postprocess: [createRemToPxProcessor()],
|
||||
})
|
||||
```
|
||||
|
||||
### Property Layer Customization
|
||||
|
||||
```ts
|
||||
presetWind4({
|
||||
preflights: {
|
||||
property: {
|
||||
// Custom parent wrapper
|
||||
parent: '@layer custom-properties',
|
||||
// Custom selector
|
||||
selector: ':where(*, ::before, ::after)',
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Remove `@supports` wrapper:
|
||||
|
||||
```ts
|
||||
presetWind4({
|
||||
preflights: {
|
||||
property: {
|
||||
parent: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Generated Layers
|
||||
|
||||
| Layer | Description | Order |
|
||||
|-------|-------------|-------|
|
||||
| `properties` | CSS `@property` rules | -200 |
|
||||
| `theme` | Theme CSS variables | -150 |
|
||||
| `base` | Reset/preflight styles | -100 |
|
||||
|
||||
## Theme.defaults
|
||||
|
||||
Global default configuration for reset styles:
|
||||
|
||||
```ts
|
||||
import type { Theme } from '@unocss/preset-wind4/theme'
|
||||
|
||||
const defaults: Theme['default'] = {
|
||||
transition: {
|
||||
duration: '150ms',
|
||||
timingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
},
|
||||
font: {
|
||||
family: 'var(--font-sans)',
|
||||
featureSettings: 'var(--font-sans--font-feature-settings)',
|
||||
variationSettings: 'var(--font-sans--font-variation-settings)',
|
||||
},
|
||||
monoFont: {
|
||||
family: 'var(--font-mono)',
|
||||
// ...
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Compatibility Notes
|
||||
|
||||
### presetRemToPx
|
||||
|
||||
Not needed - use built-in processor instead:
|
||||
|
||||
```ts
|
||||
presetWind4({
|
||||
preflights: {
|
||||
theme: {
|
||||
process: createRemToPxProcessor(),
|
||||
}
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### presetLegacyCompat
|
||||
|
||||
**Not compatible** with preset-wind4 due to `oklch` color model.
|
||||
|
||||
## Migration from Wind3
|
||||
|
||||
1. Update theme keys according to the table above
|
||||
2. Remove `@unocss/reset` imports
|
||||
3. Enable `preflights.reset: true`
|
||||
4. Test color outputs (oklch vs rgb)
|
||||
5. Update any custom theme extensions
|
||||
|
||||
```ts
|
||||
// Before (wind3)
|
||||
theme: {
|
||||
fontFamily: { sans: 'Roboto' },
|
||||
fontSize: { lg: '1.125rem' },
|
||||
breakpoints: { sm: '640px' },
|
||||
}
|
||||
|
||||
// After (wind4)
|
||||
theme: {
|
||||
font: { sans: 'Roboto' },
|
||||
text: { lg: { fontSize: '1.125rem' } },
|
||||
breakpoint: { sm: '640px' },
|
||||
}
|
||||
```
|
||||
|
||||
## When to Use Wind4
|
||||
|
||||
Choose **preset-wind4** when:
|
||||
- Starting a new project
|
||||
- Targeting modern browsers
|
||||
- Want built-in reset and CSS variables
|
||||
- Following Tailwind v4 conventions
|
||||
|
||||
Choose **preset-wind3** when:
|
||||
- Need legacy browser support
|
||||
- Migrating from Tailwind v3
|
||||
- Using presetLegacyCompat
|
||||
- Want stable, proven preset
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/presets/wind4
|
||||
-->
|
||||
156
.claude/skills/unocss/references/transformer-attributify-jsx.md
Normal file
156
.claude/skills/unocss/references/transformer-attributify-jsx.md
Normal file
@@ -0,0 +1,156 @@
|
||||
---
|
||||
name: transformer-attributify-jsx
|
||||
description: Support valueless attributify in JSX/TSX
|
||||
---
|
||||
|
||||
# Transformer Attributify JSX
|
||||
|
||||
Fixes valueless attributify mode in JSX where `<div foo>` becomes `<div foo={true}>`.
|
||||
|
||||
## The Problem
|
||||
|
||||
In JSX, valueless attributes are transformed:
|
||||
|
||||
```jsx
|
||||
// You write
|
||||
<div m-2 rounded text-teal-400 />
|
||||
|
||||
// JSX compiles to
|
||||
<div m-2={true} rounded={true} text-teal-400={true} />
|
||||
```
|
||||
|
||||
The `={true}` breaks UnoCSS attributify detection.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import {
|
||||
defineConfig,
|
||||
presetAttributify,
|
||||
transformerAttributifyJsx
|
||||
} from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetAttributify(),
|
||||
],
|
||||
transformers: [
|
||||
transformerAttributifyJsx(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
The transformer converts JSX boolean attributes back to strings:
|
||||
|
||||
```jsx
|
||||
// Input (after JSX compilation)
|
||||
<div m-2={true} rounded={true} />
|
||||
|
||||
// Output (transformed)
|
||||
<div m-2="" rounded="" />
|
||||
```
|
||||
|
||||
Now UnoCSS can properly extract the attributify classes.
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
transformerAttributifyJsx({
|
||||
// Only transform specific attributes
|
||||
// Default: transforms all that match attributify patterns
|
||||
blocklist: ['text', 'font'],
|
||||
})
|
||||
```
|
||||
|
||||
## When to Use
|
||||
|
||||
Required when using:
|
||||
- React
|
||||
- Preact
|
||||
- Solid
|
||||
- Any JSX-based framework
|
||||
|
||||
With valueless attributify syntax:
|
||||
|
||||
```jsx
|
||||
// This needs the transformer
|
||||
<div flex items-center gap-4 />
|
||||
|
||||
// This works without transformer (has values)
|
||||
<div flex="~" items="center" gap="4" />
|
||||
```
|
||||
|
||||
## Framework Setup
|
||||
|
||||
### React
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import React from '@vitejs/plugin-react'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS(), // Must be before React
|
||||
React(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// uno.config.ts
|
||||
import {
|
||||
defineConfig,
|
||||
presetAttributify,
|
||||
presetWind3,
|
||||
transformerAttributifyJsx
|
||||
} from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
presets: [
|
||||
presetWind3(),
|
||||
presetAttributify(),
|
||||
],
|
||||
transformers: [
|
||||
transformerAttributifyJsx(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Preact
|
||||
|
||||
Same as React, use `@preact/preset-vite` or `@prefresh/vite`.
|
||||
|
||||
### Solid
|
||||
|
||||
```ts
|
||||
import UnoCSS from 'unocss/vite'
|
||||
import solidPlugin from 'vite-plugin-solid'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
UnoCSS(),
|
||||
solidPlugin(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## TypeScript Support
|
||||
|
||||
Add type declarations:
|
||||
|
||||
```ts
|
||||
// shims.d.ts
|
||||
import type { AttributifyAttributes } from '@unocss/preset-attributify'
|
||||
|
||||
declare module 'react' {
|
||||
interface HTMLAttributes<T> extends AttributifyAttributes {}
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/transformers/attributify-jsx
|
||||
-->
|
||||
128
.claude/skills/unocss/references/transformer-compile-class.md
Normal file
128
.claude/skills/unocss/references/transformer-compile-class.md
Normal file
@@ -0,0 +1,128 @@
|
||||
---
|
||||
name: transformer-compile-class
|
||||
description: Compile multiple classes into one hashed class
|
||||
---
|
||||
|
||||
# Transformer Compile Class
|
||||
|
||||
Compiles multiple utility classes into a single hashed class for smaller HTML.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, transformerCompileClass } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
transformers: [
|
||||
transformerCompileClass(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Add `:uno:` prefix to mark classes for compilation:
|
||||
|
||||
```html
|
||||
<!-- Before -->
|
||||
<div class=":uno: text-center sm:text-left">
|
||||
<div class=":uno: text-sm font-bold hover:text-red" />
|
||||
</div>
|
||||
|
||||
<!-- After -->
|
||||
<div class="uno-qlmcrp">
|
||||
<div class="uno-0qw2gr" />
|
||||
</div>
|
||||
```
|
||||
|
||||
## Generated CSS
|
||||
|
||||
```css
|
||||
.uno-qlmcrp {
|
||||
text-align: center;
|
||||
}
|
||||
.uno-0qw2gr {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.uno-0qw2gr:hover {
|
||||
--un-text-opacity: 1;
|
||||
color: rgb(248 113 113 / var(--un-text-opacity));
|
||||
}
|
||||
@media (min-width: 640px) {
|
||||
.uno-qlmcrp {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```ts
|
||||
transformerCompileClass({
|
||||
// Custom trigger string (default: ':uno:')
|
||||
trigger: ':uno:',
|
||||
|
||||
// Custom class prefix (default: 'uno-')
|
||||
classPrefix: 'uno-',
|
||||
|
||||
// Hash function for class names
|
||||
hashFn: (str) => /* custom hash */,
|
||||
|
||||
// Keep original classes alongside compiled
|
||||
keepOriginal: false,
|
||||
})
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Smaller HTML** - Reduce repetitive class strings
|
||||
- **Obfuscation** - Hide utility class names in production
|
||||
- **Performance** - Fewer class attributes to parse
|
||||
|
||||
## ESLint Integration
|
||||
|
||||
Enforce compile class usage across project:
|
||||
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"@unocss/enforce-class-compile": "warn"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This rule:
|
||||
- Warns when class attribute doesn't start with `:uno:`
|
||||
- Auto-fixes by adding the prefix
|
||||
|
||||
Options:
|
||||
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"@unocss/enforce-class-compile": ["warn", {
|
||||
"prefix": ":uno:",
|
||||
"enableFix": true
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Combining with Other Transformers
|
||||
|
||||
```ts
|
||||
export default defineConfig({
|
||||
transformers: [
|
||||
transformerVariantGroup(), // Process variant groups first
|
||||
transformerDirectives(), // Then directives
|
||||
transformerCompileClass(), // Compile last
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/transformers/compile-class
|
||||
-->
|
||||
157
.claude/skills/unocss/references/transformer-directives.md
Normal file
157
.claude/skills/unocss/references/transformer-directives.md
Normal file
@@ -0,0 +1,157 @@
|
||||
---
|
||||
name: transformer-directives
|
||||
description: CSS directives @apply, @screen, theme(), and icon()
|
||||
---
|
||||
|
||||
# Transformer Directives
|
||||
|
||||
Enables `@apply`, `@screen`, `theme()`, and `icon()` directives in CSS.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, transformerDirectives } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
transformers: [
|
||||
transformerDirectives(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## @apply
|
||||
|
||||
Apply utility classes in CSS:
|
||||
|
||||
```css
|
||||
.custom-btn {
|
||||
@apply py-2 px-4 font-semibold rounded-lg;
|
||||
}
|
||||
|
||||
/* With variants - use quotes */
|
||||
.custom-btn {
|
||||
@apply 'hover:bg-blue-600 focus:ring-2';
|
||||
}
|
||||
```
|
||||
|
||||
### CSS Custom Property Alternative
|
||||
|
||||
For vanilla CSS compatibility:
|
||||
|
||||
```css
|
||||
.custom-div {
|
||||
--at-apply: text-center my-0 font-medium;
|
||||
}
|
||||
```
|
||||
|
||||
Supported aliases: `--at-apply`, `--uno-apply`, `--uno`
|
||||
|
||||
Configure aliases:
|
||||
|
||||
```ts
|
||||
transformerDirectives({
|
||||
applyVariable: ['--at-apply', '--uno-apply', '--uno'],
|
||||
// or disable: applyVariable: false
|
||||
})
|
||||
```
|
||||
|
||||
## @screen
|
||||
|
||||
Create breakpoint media queries:
|
||||
|
||||
```css
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
@screen sm {
|
||||
.grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@screen lg {
|
||||
.grid {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Breakpoint Variants
|
||||
|
||||
```css
|
||||
/* Less than breakpoint */
|
||||
@screen lt-sm {
|
||||
.item { display: none; }
|
||||
}
|
||||
|
||||
/* At specific breakpoint only */
|
||||
@screen at-md {
|
||||
.item { width: 50%; }
|
||||
}
|
||||
```
|
||||
|
||||
## theme()
|
||||
|
||||
Access theme values in CSS:
|
||||
|
||||
```css
|
||||
.btn-blue {
|
||||
background-color: theme('colors.blue.500');
|
||||
padding: theme('spacing.4');
|
||||
border-radius: theme('borderRadius.lg');
|
||||
}
|
||||
```
|
||||
|
||||
Dot notation paths into your theme config.
|
||||
|
||||
## icon()
|
||||
|
||||
Convert icon utility to SVG (requires preset-icons):
|
||||
|
||||
```css
|
||||
.icon-sun {
|
||||
background-image: icon('i-carbon-sun');
|
||||
}
|
||||
|
||||
/* With custom color */
|
||||
.icon-moon {
|
||||
background-image: icon('i-carbon-moon', '#fff');
|
||||
}
|
||||
|
||||
/* Using theme color */
|
||||
.icon-alert {
|
||||
background-image: icon('i-carbon-warning', 'theme("colors.red.500")');
|
||||
}
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
```css
|
||||
.card {
|
||||
@apply rounded-lg shadow-md p-4;
|
||||
background-color: theme('colors.white');
|
||||
}
|
||||
|
||||
.card-header {
|
||||
@apply 'font-bold text-lg border-b';
|
||||
padding-bottom: theme('spacing.2');
|
||||
}
|
||||
|
||||
@screen md {
|
||||
.card {
|
||||
@apply flex gap-4;
|
||||
}
|
||||
}
|
||||
|
||||
.card-icon {
|
||||
background-image: icon('i-carbon-document');
|
||||
@apply w-6 h-6;
|
||||
}
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/transformers/directives
|
||||
-->
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
name: transformer-variant-group
|
||||
description: Shorthand for grouping utilities with common prefixes
|
||||
---
|
||||
|
||||
# Transformer Variant Group
|
||||
|
||||
Enables shorthand syntax for grouping utilities with common prefixes.
|
||||
|
||||
## Installation
|
||||
|
||||
```ts
|
||||
import { defineConfig, transformerVariantGroup } from 'unocss'
|
||||
|
||||
export default defineConfig({
|
||||
transformers: [
|
||||
transformerVariantGroup(),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Group multiple utilities under one variant prefix using parentheses:
|
||||
|
||||
```html
|
||||
<!-- Before transformation -->
|
||||
<div class="hover:(bg-gray-400 font-medium) font-(light mono)" />
|
||||
|
||||
<!-- After transformation -->
|
||||
<div class="hover:bg-gray-400 hover:font-medium font-light font-mono" />
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Hover States
|
||||
|
||||
```html
|
||||
<button class="hover:(bg-blue-600 text-white scale-105)">
|
||||
Hover me
|
||||
</button>
|
||||
```
|
||||
|
||||
Expands to: `hover:bg-blue-600 hover:text-white hover:scale-105`
|
||||
|
||||
### Dark Mode
|
||||
|
||||
```html
|
||||
<div class="dark:(bg-gray-800 text-white)">
|
||||
Dark content
|
||||
</div>
|
||||
```
|
||||
|
||||
Expands to: `dark:bg-gray-800 dark:text-white`
|
||||
|
||||
### Responsive
|
||||
|
||||
```html
|
||||
<div class="md:(flex items-center gap-4)">
|
||||
Responsive flex
|
||||
</div>
|
||||
```
|
||||
|
||||
Expands to: `md:flex md:items-center md:gap-4`
|
||||
|
||||
### Nested Groups
|
||||
|
||||
```html
|
||||
<div class="lg:hover:(bg-blue-500 text-white)">
|
||||
Large screen hover
|
||||
</div>
|
||||
```
|
||||
|
||||
Expands to: `lg:hover:bg-blue-500 lg:hover:text-white`
|
||||
|
||||
### Multiple Prefixes
|
||||
|
||||
```html
|
||||
<div class="text-(sm gray-600) font-(medium mono)">
|
||||
Styled text
|
||||
</div>
|
||||
```
|
||||
|
||||
Expands to: `text-sm text-gray-600 font-medium font-mono`
|
||||
|
||||
## Key Points
|
||||
|
||||
- Use parentheses `()` to group utilities
|
||||
- The prefix applies to all utilities inside the group
|
||||
- Can be combined with any variant (hover, dark, responsive, etc.)
|
||||
- Nesting is supported
|
||||
- Works in class attributes and other extraction sources
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://unocss.dev/transformers/variant-group
|
||||
-->
|
||||
5
.claude/skills/vue/GENERATION.md
Normal file
5
.claude/skills/vue/GENERATION.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Generation Info
|
||||
|
||||
- **Source:** `sources/vue`
|
||||
- **Git SHA:** `dcf363038ab2f5b4571028669cf893d084b6b207`
|
||||
- **Generated:** 2026-01-28
|
||||
21
.claude/skills/vue/LICENSE.md
Normal file
21
.claude/skills/vue/LICENSE.md
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025-PRESENT Anthony Fu <https://github.com/antfu>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
63
.claude/skills/vue/SKILL.md
Normal file
63
.claude/skills/vue/SKILL.md
Normal file
@@ -0,0 +1,63 @@
|
||||
---
|
||||
name: vue
|
||||
description: Vue.js progressive JavaScript framework. Use when building Vue components, working with reactivity (ref, reactive, computed, watch), or implementing Vue Composition API patterns.
|
||||
metadata:
|
||||
author: Anthony Fu
|
||||
version: "2026.1.28"
|
||||
source: Generated from https://github.com/vuejs/docs, scripts located at https://github.com/antfu/skills
|
||||
---
|
||||
|
||||
# Vue
|
||||
|
||||
> The skill is based on Vue 3.5+, generated at 2026-01-28.
|
||||
|
||||
Vue is a progressive JavaScript framework for building user interfaces. It builds on standard HTML, CSS, and JavaScript with intuitive API and world-class documentation. The Composition API with `<script setup>` and TypeScript is the recommended approach for building Vue applications.
|
||||
|
||||
## Core References
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Reactivity System | ref, reactive, computed, watch, and watchEffect | [core-reactivity](references/core-reactivity.md) |
|
||||
|
||||
## Components
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Props | Declare and validate component props with TypeScript | [components-props](references/components-props.md) |
|
||||
| Events (Emits) | Emit custom events from components | [components-emits](references/components-emits.md) |
|
||||
| Slots | Pass template content to child components | [components-slots](references/components-slots.md) |
|
||||
| v-model | Two-way binding on custom components | [components-v-model](references/components-v-model.md) |
|
||||
| Lifecycle Hooks | Run code at specific component lifecycle stages | [components-lifecycle](references/components-lifecycle.md) |
|
||||
|
||||
## Features
|
||||
|
||||
### Script Setup & TypeScript
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Script Setup | Composition API syntactic sugar for SFCs | [features-script-setup](references/features-script-setup.md) |
|
||||
| TypeScript | Type-safe Vue components with Composition API | [features-typescript](references/features-typescript.md) |
|
||||
|
||||
### Reusability
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Composables | Encapsulate and reuse stateful logic | [features-composables](references/features-composables.md) |
|
||||
| Custom Directives | Low-level DOM manipulation directives | [features-directives](references/features-directives.md) |
|
||||
| Template Refs | Direct DOM and component instance access | [features-template-refs](references/features-template-refs.md) |
|
||||
|
||||
## Advanced
|
||||
|
||||
| Topic | Description | Reference |
|
||||
|-------|-------------|-----------|
|
||||
| Provide/Inject | Dependency injection across component tree | [advanced-provide-inject](references/advanced-provide-inject.md) |
|
||||
| Async & Suspense | Top-level await pitfalls, async components, Suspense | [advanced-async-suspense](references/advanced-async-suspense.md) |
|
||||
|
||||
## Key Recommendations
|
||||
|
||||
- **Use `<script setup lang="ts">`** for all components
|
||||
- **Prefer `ref()` over `reactive()`** for declaring state
|
||||
- **Use type-based prop declarations** with interfaces
|
||||
- **Use `defineModel()`** for v-model (3.4+)
|
||||
- **Destructure props reactively** (3.5+) for cleaner code
|
||||
- **Extract composables** for reusable stateful logic
|
||||
5
.claude/skills/vue/SYNC.md
Normal file
5
.claude/skills/vue/SYNC.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Sync Info
|
||||
|
||||
- **Source:** `vendor/antfu/skills/vue`
|
||||
- **Git SHA:** `4086f59fa12d308fb05592ca8ce1704fbb940aa3`
|
||||
- **Synced:** 2026-01-30
|
||||
246
.claude/skills/vue/references/advanced-async-suspense.md
Normal file
246
.claude/skills/vue/references/advanced-async-suspense.md
Normal file
@@ -0,0 +1,246 @@
|
||||
---
|
||||
name: async-components-suspense
|
||||
description: Handle async operations, top-level await, and Suspense boundaries
|
||||
---
|
||||
|
||||
# Async Components & Suspense
|
||||
|
||||
Vue provides patterns for handling asynchronous operations in components.
|
||||
|
||||
## Top-Level await in Script Setup
|
||||
|
||||
`<script setup>` supports top-level `await`, making the component an async dependency:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const data = await fetch('/api/data').then(r => r.json())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>{{ data }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
**Important**: Components with top-level `await` **require a `<Suspense>` boundary** in a parent component, otherwise they won't render.
|
||||
|
||||
## Suspense
|
||||
|
||||
`<Suspense>` is a built-in component for handling async dependencies in the component tree.
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<Suspense>
|
||||
<!-- Component with async setup -->
|
||||
<AsyncComponent />
|
||||
|
||||
<!-- Fallback while loading -->
|
||||
<template #fallback>
|
||||
<div>Loading...</div>
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Suspense Slots
|
||||
|
||||
- **default**: The async content to render
|
||||
- **fallback**: Content shown while async dependencies are resolving
|
||||
|
||||
```vue
|
||||
<Suspense>
|
||||
<template #default>
|
||||
<Dashboard />
|
||||
</template>
|
||||
<template #fallback>
|
||||
<LoadingSpinner />
|
||||
</template>
|
||||
</Suspense>
|
||||
```
|
||||
|
||||
## Async Components
|
||||
|
||||
Define components that are loaded asynchronously:
|
||||
|
||||
```ts
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
const AsyncModal = defineAsyncComponent(() =>
|
||||
import('./components/Modal.vue')
|
||||
)
|
||||
|
||||
// With options
|
||||
const AsyncModalWithOptions = defineAsyncComponent({
|
||||
loader: () => import('./components/Modal.vue'),
|
||||
loadingComponent: LoadingSpinner,
|
||||
errorComponent: ErrorDisplay,
|
||||
delay: 200, // Delay before showing loading (ms)
|
||||
timeout: 3000 // Timeout before showing error (ms)
|
||||
})
|
||||
```
|
||||
|
||||
## Common Async Pitfalls
|
||||
|
||||
### Pitfall 1: Missing Suspense Boundary
|
||||
|
||||
```vue
|
||||
<!-- ❌ Won't work - no Suspense boundary -->
|
||||
<template>
|
||||
<AsyncComponent />
|
||||
</template>
|
||||
|
||||
<!-- ✅ Works -->
|
||||
<template>
|
||||
<Suspense>
|
||||
<AsyncComponent />
|
||||
<template #fallback>Loading...</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Pitfall 2: Lifecycle Hooks After await
|
||||
|
||||
Lifecycle hooks must be registered synchronously, before any `await`:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
|
||||
// ✅ Register hooks BEFORE await
|
||||
onMounted(() => console.log('mounted'))
|
||||
onUnmounted(() => console.log('unmounted'))
|
||||
|
||||
// Now you can await
|
||||
const data = await fetchData()
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// ❌ WRONG - hooks after await won't work
|
||||
const data = await fetchData()
|
||||
|
||||
onMounted(() => {
|
||||
// This may not be called!
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Pitfall 3: Composables After await
|
||||
|
||||
Composables that use lifecycle hooks must be called before `await`:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useMouse } from '@/composables/useMouse'
|
||||
|
||||
// ✅ Call composables BEFORE await
|
||||
const { x, y } = useMouse()
|
||||
|
||||
const data = await fetchData()
|
||||
</script>
|
||||
```
|
||||
|
||||
### Pitfall 4: Watchers Created in Async Callbacks
|
||||
|
||||
Watchers in async callbacks aren't auto-disposed:
|
||||
|
||||
```ts
|
||||
// ❌ Memory leak - watcher not auto-disposed
|
||||
setTimeout(() => {
|
||||
watch(source, callback) // Must be stopped manually
|
||||
}, 1000)
|
||||
|
||||
// ✅ Watchers in setup are auto-disposed
|
||||
watch(source, callback)
|
||||
```
|
||||
|
||||
## Recommended Pattern: Avoid Top-Level await
|
||||
|
||||
Often better to handle async in `onMounted` or with watchers:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const data = ref<Data | null>(null)
|
||||
const isLoading = ref(true)
|
||||
const error = ref<Error | null>(null)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
data.value = await fetchData()
|
||||
} catch (e) {
|
||||
error.value = e as Error
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="isLoading">Loading...</div>
|
||||
<div v-else-if="error">Error: {{ error.message }}</div>
|
||||
<div v-else>{{ data }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
This pattern:
|
||||
- Doesn't require Suspense
|
||||
- Gives you control over loading/error states
|
||||
- Works everywhere without special parent setup
|
||||
|
||||
## When to Use Suspense
|
||||
|
||||
Use Suspense when:
|
||||
- You have nested async components
|
||||
- You want coordinated loading states across multiple async children
|
||||
- You're doing SSR with async data requirements
|
||||
|
||||
Avoid Suspense when:
|
||||
- Simple single-component async loading
|
||||
- You need fine-grained control over loading states
|
||||
- You want to avoid Suspense complexity
|
||||
|
||||
## Suspense Events
|
||||
|
||||
```vue
|
||||
<Suspense
|
||||
@pending="onPending"
|
||||
@resolve="onResolve"
|
||||
@fallback="onFallback"
|
||||
>
|
||||
<AsyncComponent />
|
||||
</Suspense>
|
||||
```
|
||||
|
||||
## Error Handling with Suspense
|
||||
|
||||
Use `onErrorCaptured` or `<ErrorBoundary>` pattern:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { onErrorCaptured, ref } from 'vue'
|
||||
|
||||
const error = ref<Error | null>(null)
|
||||
|
||||
onErrorCaptured((e) => {
|
||||
error.value = e
|
||||
return false // Prevent propagation
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="error">Error: {{ error.message }}</div>
|
||||
<Suspense v-else>
|
||||
<AsyncComponent />
|
||||
<template #fallback>Loading...</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/built-ins/suspense.html
|
||||
- https://vuejs.org/guide/components/async.html
|
||||
- https://vuejs.org/api/sfc-script-setup.html#top-level-await
|
||||
-->
|
||||
174
.claude/skills/vue/references/advanced-provide-inject.md
Normal file
174
.claude/skills/vue/references/advanced-provide-inject.md
Normal file
@@ -0,0 +1,174 @@
|
||||
---
|
||||
name: provide-inject
|
||||
description: Pass data through component tree without prop drilling
|
||||
---
|
||||
|
||||
# Provide / Inject
|
||||
|
||||
Provide data from ancestor components to any descendant, avoiding prop drilling.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```vue
|
||||
<!-- Provider.vue -->
|
||||
<script setup lang="ts">
|
||||
import { provide, ref } from 'vue'
|
||||
|
||||
const message = ref('hello')
|
||||
provide('message', message)
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- DeepChild.vue (any level deep) -->
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
|
||||
const message = inject('message')
|
||||
</script>
|
||||
```
|
||||
|
||||
## Typing with InjectionKey
|
||||
|
||||
Use `InjectionKey` for type safety between provider and injector:
|
||||
|
||||
```ts
|
||||
// keys.ts
|
||||
import type { InjectionKey, Ref } from 'vue'
|
||||
|
||||
export const messageKey = Symbol() as InjectionKey<Ref<string>>
|
||||
export const countKey = Symbol() as InjectionKey<number>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Provider.vue -->
|
||||
<script setup lang="ts">
|
||||
import { provide, ref } from 'vue'
|
||||
import { messageKey } from './keys'
|
||||
|
||||
const message = ref('hello')
|
||||
provide(messageKey, message)
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Injector.vue -->
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import { messageKey } from './keys'
|
||||
|
||||
const message = inject(messageKey) // Ref<string> | undefined
|
||||
</script>
|
||||
```
|
||||
|
||||
## Default Values
|
||||
|
||||
```ts
|
||||
// Simple default
|
||||
const value = inject('message', 'default value')
|
||||
|
||||
// Factory function (for expensive defaults)
|
||||
const value = inject('key', () => new ExpensiveClass(), true)
|
||||
// ^ treat as factory
|
||||
```
|
||||
|
||||
## App-Level Provide
|
||||
|
||||
Available to all components:
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
import { createApp } from 'vue'
|
||||
|
||||
const app = createApp(App)
|
||||
app.provide('globalConfig', { theme: 'dark' })
|
||||
```
|
||||
|
||||
## Reactive Provide/Inject
|
||||
|
||||
Provide reactive values for automatic updates:
|
||||
|
||||
```vue
|
||||
<!-- Provider.vue -->
|
||||
<script setup lang="ts">
|
||||
import { provide, ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
provide('count', count)
|
||||
</script>
|
||||
```
|
||||
|
||||
The injected value maintains reactivity connection.
|
||||
|
||||
## Mutations Best Practice
|
||||
|
||||
Keep mutations in the provider, expose update functions:
|
||||
|
||||
```vue
|
||||
<!-- Provider.vue -->
|
||||
<script setup lang="ts">
|
||||
import { provide, ref, readonly } from 'vue'
|
||||
|
||||
const location = ref('North Pole')
|
||||
|
||||
function updateLocation(newLocation: string) {
|
||||
location.value = newLocation
|
||||
}
|
||||
|
||||
provide('location', {
|
||||
location: readonly(location), // Prevent direct mutation
|
||||
updateLocation
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- Injector.vue -->
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
|
||||
const { location, updateLocation } = inject('location')!
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="updateLocation('South Pole')">
|
||||
{{ location }}
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Using Symbol Keys
|
||||
|
||||
Recommended for libraries and large apps to avoid collisions:
|
||||
|
||||
```ts
|
||||
// keys.ts
|
||||
export const myKey = Symbol('myKey')
|
||||
|
||||
// provider
|
||||
provide(myKey, value)
|
||||
|
||||
// injector
|
||||
inject(myKey)
|
||||
```
|
||||
|
||||
## Type Helpers
|
||||
|
||||
```ts
|
||||
// String key with explicit type
|
||||
const foo = inject<string>('foo')
|
||||
// ^? string | undefined
|
||||
|
||||
// With default (removes undefined)
|
||||
const foo = inject<string>('foo', 'default')
|
||||
// ^? string
|
||||
|
||||
// Force non-undefined (use when certain it's provided)
|
||||
const foo = inject('foo') as string
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/components/provide-inject.html
|
||||
- https://vuejs.org/guide/typescript/composition-api.html#typing-provide-inject
|
||||
-->
|
||||
139
.claude/skills/vue/references/components-emits.md
Normal file
139
.claude/skills/vue/references/components-emits.md
Normal file
@@ -0,0 +1,139 @@
|
||||
---
|
||||
name: component-events-emits
|
||||
description: Emit and handle custom events from child to parent components
|
||||
---
|
||||
|
||||
# Component Events
|
||||
|
||||
Components emit custom events to communicate with parent components.
|
||||
|
||||
## Emitting Events
|
||||
|
||||
Use `$emit` in templates or `defineEmits` in script:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const emit = defineEmits(['inFocus', 'submit'])
|
||||
|
||||
function handleClick() {
|
||||
emit('submit')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="$emit('inFocus')">Focus</button>
|
||||
<button @click="handleClick">Submit</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Type-Based Declaration (Recommended)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// Call signature syntax
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', id: number): void
|
||||
(e: 'update', value: string): void
|
||||
}>()
|
||||
|
||||
// Named tuple syntax (3.3+, more concise)
|
||||
const emit = defineEmits<{
|
||||
change: [id: number]
|
||||
update: [value: string]
|
||||
}>()
|
||||
|
||||
// Usage
|
||||
emit('change', 123)
|
||||
emit('update', 'hello')
|
||||
</script>
|
||||
```
|
||||
|
||||
## Event Arguments
|
||||
|
||||
Pass additional arguments to events:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const emit = defineEmits<{
|
||||
increaseBy: [amount: number]
|
||||
}>()
|
||||
|
||||
function increase() {
|
||||
emit('increaseBy', 5)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
Parent receives arguments:
|
||||
|
||||
```vue-html
|
||||
<!-- Inline handler -->
|
||||
<MyButton @increase-by="(n) => count += n" />
|
||||
|
||||
<!-- Method handler -->
|
||||
<MyButton @increase-by="increaseCount" />
|
||||
```
|
||||
|
||||
```ts
|
||||
function increaseCount(n: number) {
|
||||
count.value += n
|
||||
}
|
||||
```
|
||||
|
||||
## Event Validation
|
||||
|
||||
Validate event payloads with object syntax:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const emit = defineEmits({
|
||||
// No validation
|
||||
click: null,
|
||||
|
||||
// Validate submit event
|
||||
submit: ({ email, password }: { email: string; password: string }) => {
|
||||
if (email && password) {
|
||||
return true
|
||||
}
|
||||
console.warn('Invalid submit payload!')
|
||||
return false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Listening to Events
|
||||
|
||||
Use `v-on` or `@` shorthand:
|
||||
|
||||
```vue-html
|
||||
<MyComponent @some-event="handleEvent" />
|
||||
|
||||
<!-- With .once modifier -->
|
||||
<MyComponent @some-event.once="handleOnce" />
|
||||
```
|
||||
|
||||
## Event Name Casing
|
||||
|
||||
- Emit in camelCase
|
||||
- Listen in kebab-case
|
||||
|
||||
```ts
|
||||
emit('someEvent')
|
||||
```
|
||||
|
||||
```vue-html
|
||||
<MyComponent @some-event="handler" />
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Component events do NOT bubble (unlike DOM events)
|
||||
- Only direct child events can be listened to
|
||||
- For sibling/deeply nested communication, use provide/inject or state management
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/components/events.html
|
||||
- https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
|
||||
-->
|
||||
192
.claude/skills/vue/references/components-lifecycle.md
Normal file
192
.claude/skills/vue/references/components-lifecycle.md
Normal file
@@ -0,0 +1,192 @@
|
||||
---
|
||||
name: lifecycle-hooks
|
||||
description: Run code at specific stages of component lifecycle
|
||||
---
|
||||
|
||||
# Lifecycle Hooks
|
||||
|
||||
Execute code at specific stages of a component's lifecycle.
|
||||
|
||||
## Common Lifecycle Hooks
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
onBeforeMount,
|
||||
onMounted,
|
||||
onBeforeUpdate,
|
||||
onUpdated,
|
||||
onBeforeUnmount,
|
||||
onUnmounted
|
||||
} from 'vue'
|
||||
|
||||
// Before DOM is mounted
|
||||
onBeforeMount(() => {
|
||||
console.log('before mount')
|
||||
})
|
||||
|
||||
// After DOM is mounted (most common)
|
||||
onMounted(() => {
|
||||
console.log('mounted')
|
||||
// Safe to access DOM, make API calls, start timers
|
||||
})
|
||||
|
||||
// Before reactive state change causes re-render
|
||||
onBeforeUpdate(() => {
|
||||
console.log('before update')
|
||||
})
|
||||
|
||||
// After DOM re-render
|
||||
onUpdated(() => {
|
||||
console.log('updated')
|
||||
})
|
||||
|
||||
// Before component unmounts
|
||||
onBeforeUnmount(() => {
|
||||
console.log('before unmount')
|
||||
})
|
||||
|
||||
// After component unmounts
|
||||
onUnmounted(() => {
|
||||
console.log('unmounted')
|
||||
// Cleanup: remove listeners, cancel timers, etc.
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Lifecycle Diagram
|
||||
|
||||
```
|
||||
Creation:
|
||||
setup() → onBeforeMount → onMounted
|
||||
|
||||
Updates:
|
||||
onBeforeUpdate → onUpdated
|
||||
|
||||
Destruction:
|
||||
onBeforeUnmount → onUnmounted
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### DOM Access
|
||||
|
||||
```ts
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const inputRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
onMounted(() => {
|
||||
// DOM is available
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
```
|
||||
|
||||
### API Calls
|
||||
|
||||
```ts
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const data = ref(null)
|
||||
|
||||
onMounted(async () => {
|
||||
const response = await fetch('/api/data')
|
||||
data.value = await response.json()
|
||||
})
|
||||
```
|
||||
|
||||
### Cleanup
|
||||
|
||||
```ts
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('resize', handleResize)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
})
|
||||
```
|
||||
|
||||
### Timer Cleanup
|
||||
|
||||
```ts
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
|
||||
onMounted(() => {
|
||||
timer = setInterval(() => {
|
||||
// ...
|
||||
}, 1000)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer)
|
||||
})
|
||||
```
|
||||
|
||||
## Less Common Hooks
|
||||
|
||||
```ts
|
||||
import {
|
||||
onActivated, // Component kept alive is activated
|
||||
onDeactivated, // Component kept alive is deactivated
|
||||
onErrorCaptured, // Error from descendant captured
|
||||
onRenderTracked, // Debug: reactive dependency tracked
|
||||
onRenderTriggered // Debug: re-render triggered
|
||||
} from 'vue'
|
||||
```
|
||||
|
||||
## SSR Hooks
|
||||
|
||||
```ts
|
||||
import { onServerPrefetch } from 'vue'
|
||||
|
||||
// Only runs during server-side rendering
|
||||
onServerPrefetch(async () => {
|
||||
data.value = await fetchData()
|
||||
})
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
1. **Hooks must be called synchronously** during `setup()`:
|
||||
|
||||
```ts
|
||||
// ❌ Won't work
|
||||
setTimeout(() => {
|
||||
onMounted(() => {})
|
||||
}, 100)
|
||||
|
||||
// ✅ Works
|
||||
onMounted(() => {
|
||||
setTimeout(() => {}, 100)
|
||||
})
|
||||
```
|
||||
|
||||
2. **Can call from external functions** if called synchronously from setup:
|
||||
|
||||
```ts
|
||||
// composable.ts
|
||||
export function useFeature() {
|
||||
onMounted(() => {
|
||||
// This works if useFeature is called synchronously in setup
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
3. **Multiple calls are allowed** - all callbacks will be invoked:
|
||||
|
||||
```ts
|
||||
onMounted(() => console.log('first'))
|
||||
onMounted(() => console.log('second'))
|
||||
// Both will run
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/essentials/lifecycle.html
|
||||
- https://vuejs.org/api/composition-api-lifecycle.html
|
||||
-->
|
||||
211
.claude/skills/vue/references/components-props.md
Normal file
211
.claude/skills/vue/references/components-props.md
Normal file
@@ -0,0 +1,211 @@
|
||||
---
|
||||
name: component-props
|
||||
description: Declare and use props with type safety and validation
|
||||
---
|
||||
|
||||
# Component Props
|
||||
|
||||
Props are custom attributes for passing data from parent to child components.
|
||||
|
||||
## Type-Based Declaration (Recommended)
|
||||
|
||||
Use TypeScript interfaces with `defineProps`:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
title: string
|
||||
count?: number
|
||||
items: string[]
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Reactive Props Destructure (3.5+)
|
||||
|
||||
Destructure props while keeping reactivity:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
msg?: string
|
||||
count?: number
|
||||
}
|
||||
|
||||
const { msg = 'hello', count = 0 } = defineProps<Props>()
|
||||
|
||||
// Both msg and count are reactive
|
||||
watchEffect(() => {
|
||||
console.log(msg, count)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Passing destructured props to functions
|
||||
|
||||
```ts
|
||||
const { foo } = defineProps(['foo'])
|
||||
|
||||
// ❌ Won't work - passes value not reactive source
|
||||
watch(foo, /* ... */)
|
||||
|
||||
// ✅ Wrap in getter
|
||||
watch(() => foo, /* ... */)
|
||||
|
||||
// ✅ For composables
|
||||
useComposable(() => foo)
|
||||
```
|
||||
|
||||
## Default Values with withDefaults (3.4 and below)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
msg?: string
|
||||
labels?: string[]
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
msg: 'hello',
|
||||
labels: () => ['one', 'two'] // Factory function for objects/arrays
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Runtime Declaration
|
||||
|
||||
For runtime validation without TypeScript:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const props = defineProps({
|
||||
// Basic type check
|
||||
propA: Number,
|
||||
// Multiple types
|
||||
propB: [String, Number],
|
||||
// Required
|
||||
propC: { type: String, required: true },
|
||||
// With default
|
||||
propD: { type: Number, default: 100 },
|
||||
// Object with factory default
|
||||
propE: {
|
||||
type: Object,
|
||||
default: () => ({ message: 'hello' })
|
||||
},
|
||||
// Custom validator
|
||||
propF: {
|
||||
validator(value: string) {
|
||||
return ['success', 'warning', 'danger'].includes(value)
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Prop Types
|
||||
|
||||
Supported `type` values:
|
||||
- `String`, `Number`, `Boolean`, `Array`, `Object`
|
||||
- `Date`, `Function`, `Symbol`, `Error`
|
||||
- Custom classes (uses `instanceof`)
|
||||
|
||||
```ts
|
||||
class Person {
|
||||
constructor(public name: string) {}
|
||||
}
|
||||
|
||||
defineProps({
|
||||
author: Person // instanceof check
|
||||
})
|
||||
```
|
||||
|
||||
## Nullable Props
|
||||
|
||||
```ts
|
||||
defineProps({
|
||||
id: {
|
||||
type: [String, null],
|
||||
required: true
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Boolean Casting
|
||||
|
||||
Boolean props have special casting rules:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
defineProps({
|
||||
disabled: Boolean
|
||||
})
|
||||
</script>
|
||||
|
||||
<!-- equivalent to :disabled="true" -->
|
||||
<MyComponent disabled />
|
||||
|
||||
<!-- equivalent to :disabled="false" -->
|
||||
<MyComponent />
|
||||
```
|
||||
|
||||
## One-Way Data Flow
|
||||
|
||||
Props form a one-way binding: parent → child. Never mutate props directly.
|
||||
|
||||
```ts
|
||||
const props = defineProps(['initialCounter'])
|
||||
|
||||
// ❌ Don't mutate props
|
||||
props.initialCounter = 5
|
||||
|
||||
// ✅ Use local state initialized from prop
|
||||
const counter = ref(props.initialCounter)
|
||||
|
||||
// ✅ Or use computed for transformations
|
||||
const normalizedSize = computed(() => props.size.trim().toLowerCase())
|
||||
```
|
||||
|
||||
## Passing Props
|
||||
|
||||
```vue-html
|
||||
<!-- Static -->
|
||||
<BlogPost title="My Post" />
|
||||
|
||||
<!-- Dynamic -->
|
||||
<BlogPost :title="post.title" />
|
||||
|
||||
<!-- Number (requires v-bind) -->
|
||||
<BlogPost :likes="42" />
|
||||
|
||||
<!-- Boolean -->
|
||||
<BlogPost is-published />
|
||||
<BlogPost :is-published="false" />
|
||||
|
||||
<!-- Object spread -->
|
||||
<BlogPost v-bind="post" />
|
||||
<!-- equivalent to -->
|
||||
<BlogPost :id="post.id" :title="post.title" />
|
||||
```
|
||||
|
||||
## Prop Name Casing
|
||||
|
||||
- Declare with camelCase in JavaScript
|
||||
- Use kebab-case in templates
|
||||
|
||||
```ts
|
||||
defineProps({
|
||||
greetingMessage: String
|
||||
})
|
||||
```
|
||||
|
||||
```vue-html
|
||||
<MyComponent greeting-message="hello" />
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/components/props.html
|
||||
- https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
|
||||
-->
|
||||
201
.claude/skills/vue/references/components-slots.md
Normal file
201
.claude/skills/vue/references/components-slots.md
Normal file
@@ -0,0 +1,201 @@
|
||||
---
|
||||
name: component-slots
|
||||
description: Pass template content to child components with default, named, and scoped slots
|
||||
---
|
||||
|
||||
# Component Slots
|
||||
|
||||
Slots allow parent components to pass template content into child components.
|
||||
|
||||
## Basic Slot
|
||||
|
||||
Child component with slot outlet:
|
||||
|
||||
```vue
|
||||
<!-- FancyButton.vue -->
|
||||
<template>
|
||||
<button class="fancy-btn">
|
||||
<slot></slot> <!-- slot outlet -->
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
Parent passes slot content:
|
||||
|
||||
```vue-html
|
||||
<FancyButton>
|
||||
Click me!
|
||||
</FancyButton>
|
||||
```
|
||||
|
||||
Renders as:
|
||||
|
||||
```html
|
||||
<button class="fancy-btn">Click me!</button>
|
||||
```
|
||||
|
||||
## Fallback Content
|
||||
|
||||
Provide default content when no slot content is provided:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<button>
|
||||
<slot>Submit</slot> <!-- "Submit" is fallback -->
|
||||
</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Named Slots
|
||||
|
||||
Use multiple slots with names:
|
||||
|
||||
```vue
|
||||
<!-- BaseLayout.vue -->
|
||||
<template>
|
||||
<div class="container">
|
||||
<header>
|
||||
<slot name="header"></slot>
|
||||
</header>
|
||||
<main>
|
||||
<slot></slot> <!-- default slot -->
|
||||
</main>
|
||||
<footer>
|
||||
<slot name="footer"></slot>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
Use `v-slot` or `#` shorthand to target named slots:
|
||||
|
||||
```vue-html
|
||||
<BaseLayout>
|
||||
<template #header>
|
||||
<h1>Page Title</h1>
|
||||
</template>
|
||||
|
||||
<p>Main content goes here</p>
|
||||
|
||||
<template #footer>
|
||||
<p>Contact info</p>
|
||||
</template>
|
||||
</BaseLayout>
|
||||
```
|
||||
|
||||
## Scoped Slots
|
||||
|
||||
Pass data from child to parent slot content:
|
||||
|
||||
```vue
|
||||
<!-- MyComponent.vue -->
|
||||
<template>
|
||||
<div>
|
||||
<slot :text="greetingMessage" :count="1"></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const greetingMessage = 'hello'
|
||||
</script>
|
||||
```
|
||||
|
||||
Receive slot props in parent:
|
||||
|
||||
```vue-html
|
||||
<MyComponent v-slot="slotProps">
|
||||
{{ slotProps.text }} {{ slotProps.count }}
|
||||
</MyComponent>
|
||||
|
||||
<!-- Or with destructuring -->
|
||||
<MyComponent v-slot="{ text, count }">
|
||||
{{ text }} {{ count }}
|
||||
</MyComponent>
|
||||
```
|
||||
|
||||
### Named Scoped Slots
|
||||
|
||||
```vue-html
|
||||
<MyComponent>
|
||||
<template #header="headerProps">
|
||||
{{ headerProps.title }}
|
||||
</template>
|
||||
|
||||
<template #default="{ message }">
|
||||
{{ message }}
|
||||
</template>
|
||||
</MyComponent>
|
||||
```
|
||||
|
||||
## Conditional Slots
|
||||
|
||||
Check if a slot has content using `$slots`:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="card">
|
||||
<div v-if="$slots.header" class="card-header">
|
||||
<slot name="header" />
|
||||
</div>
|
||||
|
||||
<div v-if="$slots.default" class="card-content">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Dynamic Slot Names
|
||||
|
||||
```vue-html
|
||||
<template #[dynamicSlotName]>
|
||||
...
|
||||
</template>
|
||||
```
|
||||
|
||||
## Renderless Components
|
||||
|
||||
Components that only provide logic via scoped slots:
|
||||
|
||||
```vue
|
||||
<!-- MouseTracker.vue -->
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
function update(e: MouseEvent) {
|
||||
x.value = e.pageX
|
||||
y.value = e.pageY
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('mousemove', update))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', update))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<slot :x="x" :y="y"></slot>
|
||||
</template>
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```vue-html
|
||||
<MouseTracker v-slot="{ x, y }">
|
||||
Mouse: {{ x }}, {{ y }}
|
||||
</MouseTracker>
|
||||
```
|
||||
|
||||
> Note: Composables are often preferred over renderless components for pure logic reuse.
|
||||
|
||||
## Render Scope
|
||||
|
||||
- Slot content has access to parent scope
|
||||
- Slot content does NOT have access to child scope
|
||||
- Use scoped slots to expose child data
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/components/slots.html
|
||||
-->
|
||||
183
.claude/skills/vue/references/components-v-model.md
Normal file
183
.claude/skills/vue/references/components-v-model.md
Normal file
@@ -0,0 +1,183 @@
|
||||
---
|
||||
name: component-v-model
|
||||
description: Implement two-way data binding on custom components
|
||||
---
|
||||
|
||||
# Component v-model
|
||||
|
||||
Create two-way bindings between parent and child components.
|
||||
|
||||
## defineModel() (3.4+, Recommended)
|
||||
|
||||
The simplest way to implement v-model:
|
||||
|
||||
```vue
|
||||
<!-- Child.vue -->
|
||||
<script setup lang="ts">
|
||||
const model = defineModel<string>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="model" />
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue-html
|
||||
<!-- Parent.vue -->
|
||||
<Child v-model="searchText" />
|
||||
```
|
||||
|
||||
`defineModel()` returns a ref that:
|
||||
- Syncs with parent's bound value
|
||||
- Emits `update:modelValue` when mutated
|
||||
|
||||
### With Options
|
||||
|
||||
```ts
|
||||
// Required model
|
||||
const model = defineModel<string>({ required: true })
|
||||
|
||||
// With default
|
||||
const model = defineModel<number>({ default: 0 })
|
||||
```
|
||||
|
||||
## Named v-model
|
||||
|
||||
Use arguments for multiple v-models:
|
||||
|
||||
```vue
|
||||
<!-- UserName.vue -->
|
||||
<script setup lang="ts">
|
||||
const firstName = defineModel<string>('firstName')
|
||||
const lastName = defineModel<string>('lastName')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="firstName" />
|
||||
<input v-model="lastName" />
|
||||
</template>
|
||||
```
|
||||
|
||||
```vue-html
|
||||
<UserName
|
||||
v-model:first-name="first"
|
||||
v-model:last-name="last"
|
||||
/>
|
||||
```
|
||||
|
||||
## v-model Modifiers
|
||||
|
||||
Access and handle modifiers:
|
||||
|
||||
```vue-html
|
||||
<MyComponent v-model.capitalize="text" />
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const [model, modifiers] = defineModel<string>()
|
||||
|
||||
console.log(modifiers) // { capitalize: true }
|
||||
</script>
|
||||
```
|
||||
|
||||
### Transform with Modifiers
|
||||
|
||||
Use `get` and `set` options:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const [model, modifiers] = defineModel<string>({
|
||||
set(value) {
|
||||
if (modifiers.capitalize) {
|
||||
return value.charAt(0).toUpperCase() + value.slice(1)
|
||||
}
|
||||
return value
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="model" />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Modifiers with Named v-model
|
||||
|
||||
```vue-html
|
||||
<MyComponent v-model:title.capitalize="title" />
|
||||
```
|
||||
|
||||
```ts
|
||||
const [title, titleModifiers] = defineModel<string>('title')
|
||||
console.log(titleModifiers) // { capitalize: true }
|
||||
```
|
||||
|
||||
## Manual Implementation (Pre-3.4)
|
||||
|
||||
Understanding what `defineModel` does under the hood:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
modelValue: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input
|
||||
:value="props.modelValue"
|
||||
@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
For named v-model `v-model:title`:
|
||||
|
||||
```ts
|
||||
defineProps<{ title: string }>()
|
||||
defineEmits<{ 'update:title': [value: string] }>()
|
||||
```
|
||||
|
||||
## Typing defineModel
|
||||
|
||||
```ts
|
||||
// Basic
|
||||
const model = defineModel<string>()
|
||||
// ^? Ref<string | undefined>
|
||||
|
||||
// Required (removes undefined)
|
||||
const model = defineModel<string>({ required: true })
|
||||
// ^? Ref<string>
|
||||
|
||||
// With modifiers
|
||||
const [model, modifiers] = defineModel<string, 'trim' | 'capitalize'>()
|
||||
// ^? Record<'trim' | 'capitalize', true | undefined>
|
||||
```
|
||||
|
||||
## Warning: Default Values
|
||||
|
||||
Having a default in `defineModel` without providing a value from parent causes desync:
|
||||
|
||||
```vue
|
||||
<!-- Child: model is 1 -->
|
||||
<script setup>
|
||||
const model = defineModel({ default: 1 })
|
||||
</script>
|
||||
|
||||
<!-- Parent: myRef is undefined -->
|
||||
<script setup>
|
||||
const myRef = ref()
|
||||
</script>
|
||||
<Child v-model="myRef" />
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/components/v-model.html
|
||||
- https://vuejs.org/api/sfc-script-setup.html#definemodel
|
||||
-->
|
||||
289
.claude/skills/vue/references/core-reactivity.md
Normal file
289
.claude/skills/vue/references/core-reactivity.md
Normal file
@@ -0,0 +1,289 @@
|
||||
---
|
||||
name: vue-reactivity-system
|
||||
description: Core reactivity primitives - ref, reactive, computed, and watchers
|
||||
---
|
||||
|
||||
# Vue Reactivity System
|
||||
|
||||
Vue's reactivity system enables automatic tracking of state changes and DOM updates.
|
||||
|
||||
## ref()
|
||||
|
||||
Create reactive primitive values with `ref()`. Access/modify via `.value` in JavaScript, auto-unwrapped in templates.
|
||||
|
||||
```ts
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
console.log(count.value) // 0
|
||||
count.value++
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="increment">{{ count }}</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Typing refs
|
||||
|
||||
```ts
|
||||
import { ref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
// Type inference
|
||||
const year = ref(2020) // Ref<number>
|
||||
|
||||
// Explicit generic
|
||||
const name = ref<string | null>(null)
|
||||
|
||||
// Ref type annotation
|
||||
const id: Ref<string | number> = ref('abc')
|
||||
```
|
||||
|
||||
## reactive()
|
||||
|
||||
Create reactive objects. No `.value` needed, but cannot reassign the entire object.
|
||||
|
||||
```ts
|
||||
import { reactive } from 'vue'
|
||||
|
||||
interface State {
|
||||
count: number
|
||||
name: string
|
||||
}
|
||||
|
||||
const state: State = reactive({
|
||||
count: 0,
|
||||
name: 'Vue'
|
||||
})
|
||||
|
||||
state.count++ // reactive
|
||||
```
|
||||
|
||||
### Limitations of reactive()
|
||||
|
||||
1. **Only works with objects** - not primitives
|
||||
2. **Cannot replace entire object** - loses reactivity
|
||||
3. **Destructuring loses reactivity** - use `toRefs()` instead
|
||||
|
||||
```ts
|
||||
const state = reactive({ count: 0 })
|
||||
|
||||
// ❌ Loses reactivity
|
||||
let { count } = state
|
||||
|
||||
// ✅ Use toRefs
|
||||
import { toRefs } from 'vue'
|
||||
const { count } = toRefs(state)
|
||||
```
|
||||
|
||||
## Recommendation
|
||||
|
||||
Use `ref()` as the primary API for declaring reactive state - it works with any value type and has consistent behavior.
|
||||
|
||||
## Deep Reactivity
|
||||
|
||||
Both `ref()` and `reactive()` are deeply reactive by default:
|
||||
|
||||
```ts
|
||||
const obj = ref({
|
||||
nested: { count: 0 },
|
||||
arr: ['foo', 'bar']
|
||||
})
|
||||
|
||||
// These trigger updates
|
||||
obj.value.nested.count++
|
||||
obj.value.arr.push('baz')
|
||||
```
|
||||
|
||||
Use `shallowRef()` or `shallowReactive()` to opt out of deep reactivity for performance.
|
||||
|
||||
## DOM Update Timing
|
||||
|
||||
DOM updates are batched and asynchronous. Use `nextTick()` to wait for updates:
|
||||
|
||||
```ts
|
||||
import { ref, nextTick } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
|
||||
async function increment() {
|
||||
count.value++
|
||||
await nextTick()
|
||||
// DOM is now updated
|
||||
}
|
||||
```
|
||||
|
||||
## Ref Unwrapping Rules
|
||||
|
||||
- **In templates**: Top-level refs auto-unwrap
|
||||
- **In reactive objects**: Refs auto-unwrap when accessed as properties
|
||||
- **In arrays/collections**: Refs do NOT auto-unwrap
|
||||
|
||||
```ts
|
||||
const count = ref(0)
|
||||
const state = reactive({ count })
|
||||
|
||||
console.log(state.count) // 0 (unwrapped)
|
||||
|
||||
const books = reactive([ref('Vue Guide')])
|
||||
console.log(books[0].value) // Need .value
|
||||
```
|
||||
|
||||
## computed()
|
||||
|
||||
Derive values from reactive state with automatic caching. Only re-evaluates when dependencies change.
|
||||
|
||||
```ts
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const firstName = ref('John')
|
||||
const lastName = ref('Doe')
|
||||
|
||||
// Readonly computed
|
||||
const fullName = computed(() => `${firstName.value} ${lastName.value}`)
|
||||
|
||||
// Writable computed
|
||||
const fullNameWritable = computed({
|
||||
get() {
|
||||
return `${firstName.value} ${lastName.value}`
|
||||
},
|
||||
set(newValue: string) {
|
||||
[firstName.value, lastName.value] = newValue.split(' ')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Computed Best Practices
|
||||
|
||||
- **Getters should be pure** - no side effects, no mutating other state
|
||||
- **Don't mutate computed values** - mutate the source instead
|
||||
- **Use computed over methods** for derived data (caching benefit)
|
||||
|
||||
```ts
|
||||
// ✅ Cached - only recalculates when items changes
|
||||
const activeItems = computed(() => items.value.filter(x => x.active))
|
||||
|
||||
// ❌ Not cached - runs on every render
|
||||
function getActiveItems() {
|
||||
return items.value.filter(x => x.active)
|
||||
}
|
||||
```
|
||||
|
||||
## watch()
|
||||
|
||||
Explicitly watch reactive sources and run side effects when they change. Lazy by default.
|
||||
|
||||
```ts
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
const id = ref(1)
|
||||
|
||||
watch(id, async (newId, oldId) => {
|
||||
const data = await fetchData(newId)
|
||||
// handle data...
|
||||
})
|
||||
```
|
||||
|
||||
### Watch Source Types
|
||||
|
||||
```ts
|
||||
const x = ref(0)
|
||||
const obj = reactive({ count: 0 })
|
||||
|
||||
// Single ref
|
||||
watch(x, (newX) => console.log(newX))
|
||||
|
||||
// Getter function
|
||||
watch(() => obj.count, (count) => console.log(count))
|
||||
|
||||
// Multiple sources
|
||||
watch([x, () => obj.count], ([newX, newCount]) => {
|
||||
console.log(newX, newCount)
|
||||
})
|
||||
```
|
||||
|
||||
### Watch Options
|
||||
|
||||
```ts
|
||||
watch(source, callback, {
|
||||
immediate: true, // Run immediately on creation
|
||||
deep: true, // Watch nested properties
|
||||
once: true, // Trigger only once (3.4+)
|
||||
flush: 'post' // Run after DOM update
|
||||
})
|
||||
```
|
||||
|
||||
## watchEffect()
|
||||
|
||||
Automatically tracks dependencies and runs immediately. Re-runs when any tracked dependency changes.
|
||||
|
||||
```ts
|
||||
import { ref, watchEffect } from 'vue'
|
||||
|
||||
const todoId = ref(1)
|
||||
const data = ref(null)
|
||||
|
||||
watchEffect(async () => {
|
||||
const response = await fetch(`/api/todos/${todoId.value}`)
|
||||
data.value = await response.json()
|
||||
})
|
||||
```
|
||||
|
||||
### watch vs watchEffect
|
||||
|
||||
| Feature | watch | watchEffect |
|
||||
|---------|-------|-------------|
|
||||
| Dependency tracking | Explicit | Automatic |
|
||||
| Lazy | Yes | No (immediate) |
|
||||
| Access old value | Yes | No |
|
||||
| Best for | Specific sources | Multiple dependencies |
|
||||
|
||||
## Watcher Cleanup (3.5+)
|
||||
|
||||
Cancel stale async operations:
|
||||
|
||||
```ts
|
||||
import { watch, onWatcherCleanup } from 'vue'
|
||||
|
||||
watch(id, async (newId) => {
|
||||
const controller = new AbortController()
|
||||
|
||||
fetch(`/api/${newId}`, { signal: controller.signal })
|
||||
|
||||
onWatcherCleanup(() => controller.abort())
|
||||
})
|
||||
```
|
||||
|
||||
## Stopping Watchers
|
||||
|
||||
```ts
|
||||
const stop = watch(source, callback)
|
||||
const stop2 = watchEffect(() => { /* ... */ })
|
||||
|
||||
// Stop manually
|
||||
stop()
|
||||
stop2()
|
||||
|
||||
// Pause/Resume (3.5+)
|
||||
const { stop, pause, resume } = watchEffect(() => { /* ... */ })
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/essentials/reactivity-fundamentals.html
|
||||
- https://vuejs.org/guide/essentials/computed.html
|
||||
- https://vuejs.org/guide/essentials/watchers.html
|
||||
- https://vuejs.org/api/reactivity-core.html
|
||||
-->
|
||||
262
.claude/skills/vue/references/features-composables.md
Normal file
262
.claude/skills/vue/references/features-composables.md
Normal file
@@ -0,0 +1,262 @@
|
||||
---
|
||||
name: composables
|
||||
description: Encapsulate and reuse stateful logic with the Composition API
|
||||
---
|
||||
|
||||
# Composables
|
||||
|
||||
Composables are functions that encapsulate and reuse stateful logic using Composition API.
|
||||
|
||||
## What is a Composable?
|
||||
|
||||
A composable is a function that:
|
||||
- Uses Composition API functions (ref, computed, onMounted, etc.)
|
||||
- Manages reactive state
|
||||
- Returns reactive state and/or functions
|
||||
- Name starts with "use" by convention
|
||||
|
||||
## Basic Example
|
||||
|
||||
```ts
|
||||
// composables/useMouse.ts
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
export function useMouse() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
function update(event: MouseEvent) {
|
||||
x.value = event.pageX
|
||||
y.value = event.pageY
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('mousemove', update))
|
||||
onUnmounted(() => window.removeEventListener('mousemove', update))
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useMouse } from '@/composables/useMouse'
|
||||
|
||||
const { x, y } = useMouse()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
Mouse: {{ x }}, {{ y }}
|
||||
</template>
|
||||
```
|
||||
|
||||
## Async Composable
|
||||
|
||||
Handle async data fetching:
|
||||
|
||||
```ts
|
||||
// composables/useFetch.ts
|
||||
import { ref, watchEffect, toValue, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useFetch<T>(url: MaybeRefOrGetter<string>) {
|
||||
const data = ref<T | null>(null)
|
||||
const error = ref<Error | null>(null)
|
||||
const isLoading = ref(false)
|
||||
|
||||
watchEffect(async () => {
|
||||
data.value = null
|
||||
error.value = null
|
||||
isLoading.value = true
|
||||
|
||||
try {
|
||||
const response = await fetch(toValue(url))
|
||||
data.value = await response.json()
|
||||
} catch (e) {
|
||||
error.value = e as Error
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
return { data, error, isLoading }
|
||||
}
|
||||
```
|
||||
|
||||
Usage with reactive URL:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useFetch } from '@/composables/useFetch'
|
||||
|
||||
const userId = ref(1)
|
||||
const { data, error, isLoading } = useFetch(() => `/api/users/${userId.value}`)
|
||||
|
||||
// Changing userId triggers refetch
|
||||
function nextUser() {
|
||||
userId.value++
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Composable Conventions
|
||||
|
||||
### Naming
|
||||
|
||||
- Always start with `use` (useMouse, useFetch, useCounter)
|
||||
- Use camelCase
|
||||
|
||||
### Input Arguments
|
||||
|
||||
Accept refs or getters for reactivity:
|
||||
|
||||
```ts
|
||||
import { toValue, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
function useFeature(input: MaybeRefOrGetter<string>) {
|
||||
// toValue handles ref, getter, or plain value
|
||||
const value = toValue(input)
|
||||
|
||||
// For reactive tracking, call toValue inside watchEffect/computed
|
||||
watchEffect(() => {
|
||||
console.log(toValue(input))
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Return Values
|
||||
|
||||
Return a plain object with refs (not reactive):
|
||||
|
||||
```ts
|
||||
// ✅ Good - refs can be destructured
|
||||
export function useCounter() {
|
||||
const count = ref(0)
|
||||
const increment = () => count.value++
|
||||
|
||||
return { count, increment }
|
||||
}
|
||||
|
||||
// Usage - maintains reactivity
|
||||
const { count, increment } = useCounter()
|
||||
```
|
||||
|
||||
```ts
|
||||
// ❌ Avoid - reactive loses connection on destructure
|
||||
export function useCounter() {
|
||||
const state = reactive({ count: 0 })
|
||||
return state
|
||||
}
|
||||
|
||||
// Loses reactivity
|
||||
const { count } = useCounter()
|
||||
```
|
||||
|
||||
## Composing Composables
|
||||
|
||||
Composables can use other composables:
|
||||
|
||||
```ts
|
||||
// composables/useEventListener.ts
|
||||
import { onMounted, onUnmounted, type MaybeRefOrGetter, toValue } from 'vue'
|
||||
|
||||
export function useEventListener(
|
||||
target: MaybeRefOrGetter<EventTarget>,
|
||||
event: string,
|
||||
callback: EventListener
|
||||
) {
|
||||
onMounted(() => toValue(target).addEventListener(event, callback))
|
||||
onUnmounted(() => toValue(target).removeEventListener(event, callback))
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// composables/useMouse.ts - using useEventListener
|
||||
import { ref } from 'vue'
|
||||
import { useEventListener } from './useEventListener'
|
||||
|
||||
export function useMouse() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
useEventListener(window, 'mousemove', (event) => {
|
||||
x.value = (event as MouseEvent).pageX
|
||||
y.value = (event as MouseEvent).pageY
|
||||
})
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
```
|
||||
|
||||
## Side Effects
|
||||
|
||||
### SSR Considerations
|
||||
|
||||
Run DOM-specific code only in browser:
|
||||
|
||||
```ts
|
||||
export function useWindowSize() {
|
||||
const width = ref(0)
|
||||
const height = ref(0)
|
||||
|
||||
onMounted(() => {
|
||||
// Only runs in browser
|
||||
width.value = window.innerWidth
|
||||
height.value = window.innerHeight
|
||||
})
|
||||
|
||||
return { width, height }
|
||||
}
|
||||
```
|
||||
|
||||
### Cleanup
|
||||
|
||||
Always clean up side effects:
|
||||
|
||||
```ts
|
||||
export function useInterval(callback: () => void, delay: number) {
|
||||
const id = ref<number | undefined>()
|
||||
|
||||
onMounted(() => {
|
||||
id.value = setInterval(callback, delay)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (id.value) clearInterval(id.value)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Usage Restrictions
|
||||
|
||||
Composables must be called:
|
||||
- Synchronously in `<script setup>` or `setup()`
|
||||
- Can be called in lifecycle hooks like `onMounted()`
|
||||
|
||||
```ts
|
||||
// ✅ Works
|
||||
<script setup>
|
||||
const { x, y } = useMouse()
|
||||
</script>
|
||||
|
||||
// ❌ Won't work
|
||||
setTimeout(() => {
|
||||
const { x, y } = useMouse() // No active component
|
||||
}, 100)
|
||||
```
|
||||
|
||||
Exception: `<script setup>` allows composables after `await`.
|
||||
|
||||
## vs Other Patterns
|
||||
|
||||
**vs Mixins**: Composables are explicit (no naming collisions, clear source)
|
||||
|
||||
**vs Renderless Components**: Composables have no component overhead
|
||||
|
||||
**vs React Hooks**: Similar concept, but Vue's reactivity is different - no rules about hook order or dependency arrays
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/reusability/composables.html
|
||||
-->
|
||||
224
.claude/skills/vue/references/features-directives.md
Normal file
224
.claude/skills/vue/references/features-directives.md
Normal file
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: custom-directives
|
||||
description: Create reusable directives for low-level DOM manipulation
|
||||
---
|
||||
|
||||
# Custom Directives
|
||||
|
||||
Custom directives provide low-level DOM access for reusable behavior.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use custom directives when:
|
||||
- You need direct DOM manipulation
|
||||
- The behavior can't be achieved with components or composables
|
||||
- You need to apply behavior to native elements
|
||||
|
||||
## Basic Example
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// v-focus directive
|
||||
const vFocus = {
|
||||
mounted: (el: HTMLElement) => el.focus()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-focus />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Directive Hooks
|
||||
|
||||
```ts
|
||||
const myDirective = {
|
||||
// Before element attributes/listeners are applied
|
||||
created(el, binding, vnode) {},
|
||||
|
||||
// Before element is inserted into DOM
|
||||
beforeMount(el, binding, vnode) {},
|
||||
|
||||
// After element and children are mounted
|
||||
mounted(el, binding, vnode) {},
|
||||
|
||||
// Before parent component updates
|
||||
beforeUpdate(el, binding, vnode, prevVnode) {},
|
||||
|
||||
// After parent component updates
|
||||
updated(el, binding, vnode, prevVnode) {},
|
||||
|
||||
// Before parent component unmounts
|
||||
beforeUnmount(el, binding, vnode) {},
|
||||
|
||||
// After parent component unmounts
|
||||
unmounted(el, binding, vnode) {}
|
||||
}
|
||||
```
|
||||
|
||||
## Hook Arguments
|
||||
|
||||
```ts
|
||||
interface DirectiveBinding<T = any> {
|
||||
value: T // v-my-dir="value"
|
||||
oldValue: T // Previous value (beforeUpdate/updated only)
|
||||
arg?: string // v-my-dir:arg
|
||||
modifiers: Record<string, boolean> // v-my-dir.foo.bar → { foo: true, bar: true }
|
||||
instance: ComponentPublicInstance // Component using the directive
|
||||
dir: ObjectDirective // Directive definition object
|
||||
}
|
||||
```
|
||||
|
||||
Example usage:
|
||||
|
||||
```vue-html
|
||||
<div v-example:foo.bar="baz">
|
||||
```
|
||||
|
||||
```ts
|
||||
// binding object:
|
||||
{
|
||||
arg: 'foo',
|
||||
modifiers: { bar: true },
|
||||
value: /* value of baz */,
|
||||
oldValue: /* previous value */
|
||||
}
|
||||
```
|
||||
|
||||
## Function Shorthand
|
||||
|
||||
When you only need `mounted` and `updated` with same behavior:
|
||||
|
||||
```ts
|
||||
// Full form
|
||||
const vColor = {
|
||||
mounted(el, binding) {
|
||||
el.style.color = binding.value
|
||||
},
|
||||
updated(el, binding) {
|
||||
el.style.color = binding.value
|
||||
}
|
||||
}
|
||||
|
||||
// Shorthand (same behavior)
|
||||
const vColor = (el: HTMLElement, binding: DirectiveBinding<string>) => {
|
||||
el.style.color = binding.value
|
||||
}
|
||||
```
|
||||
|
||||
## Global Registration
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
const app = createApp(App)
|
||||
|
||||
app.directive('focus', {
|
||||
mounted: (el) => el.focus()
|
||||
})
|
||||
|
||||
// Shorthand
|
||||
app.directive('color', (el, binding) => {
|
||||
el.style.color = binding.value
|
||||
})
|
||||
```
|
||||
|
||||
## Object Literals
|
||||
|
||||
Pass multiple values:
|
||||
|
||||
```vue-html
|
||||
<div v-demo="{ color: 'white', text: 'hello' }">
|
||||
```
|
||||
|
||||
```ts
|
||||
const vDemo = (el: HTMLElement, binding: DirectiveBinding<{ color: string; text: string }>) => {
|
||||
console.log(binding.value.color) // 'white'
|
||||
console.log(binding.value.text) // 'hello'
|
||||
}
|
||||
```
|
||||
|
||||
## Dynamic Arguments
|
||||
|
||||
```vue-html
|
||||
<div v-my-directive:[dynamicArg]="value">
|
||||
```
|
||||
|
||||
## Practical Examples
|
||||
|
||||
### v-click-outside
|
||||
|
||||
```ts
|
||||
const vClickOutside = {
|
||||
mounted(el: HTMLElement, binding: DirectiveBinding<() => void>) {
|
||||
el._clickOutside = (event: MouseEvent) => {
|
||||
if (!el.contains(event.target as Node)) {
|
||||
binding.value()
|
||||
}
|
||||
}
|
||||
document.addEventListener('click', el._clickOutside)
|
||||
},
|
||||
unmounted(el: HTMLElement) {
|
||||
document.removeEventListener('click', el._clickOutside)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### v-tooltip
|
||||
|
||||
```ts
|
||||
const vTooltip = {
|
||||
mounted(el: HTMLElement, binding: DirectiveBinding<string>) {
|
||||
el.setAttribute('title', binding.value)
|
||||
},
|
||||
updated(el: HTMLElement, binding: DirectiveBinding<string>) {
|
||||
el.setAttribute('title', binding.value)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### v-permission
|
||||
|
||||
```ts
|
||||
const vPermission = {
|
||||
mounted(el: HTMLElement, binding: DirectiveBinding<string>) {
|
||||
if (!hasPermission(binding.value)) {
|
||||
el.parentNode?.removeChild(el)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## TypeScript: Global Directives
|
||||
|
||||
```ts
|
||||
// directives/highlight.ts
|
||||
import type { Directive } from 'vue'
|
||||
|
||||
export type HighlightDirective = Directive<HTMLElement, string>
|
||||
|
||||
declare module 'vue' {
|
||||
export interface ComponentCustomProperties {
|
||||
vHighlight: HighlightDirective
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
mounted: (el, binding) => {
|
||||
el.style.backgroundColor = binding.value
|
||||
}
|
||||
} satisfies HighlightDirective
|
||||
```
|
||||
|
||||
## Usage on Components
|
||||
|
||||
⚠️ **Not recommended** - directives apply to root element, which can be unpredictable with multi-root components.
|
||||
|
||||
```vue-html
|
||||
<!-- Applies to MyComponent's root element -->
|
||||
<MyComponent v-my-directive />
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/reusability/custom-directives.html
|
||||
-->
|
||||
247
.claude/skills/vue/references/features-script-setup.md
Normal file
247
.claude/skills/vue/references/features-script-setup.md
Normal file
@@ -0,0 +1,247 @@
|
||||
---
|
||||
name: script-setup
|
||||
description: Compile-time syntactic sugar for Composition API in SFCs
|
||||
---
|
||||
|
||||
# Script Setup
|
||||
|
||||
`<script setup>` is the recommended syntax for Composition API in Single-File Components.
|
||||
|
||||
## Basic Syntax
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="increment">{{ count }}</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
- Less boilerplate (no `export default`, no `return`)
|
||||
- TypeScript type inference
|
||||
- Better runtime performance
|
||||
- Better IDE support
|
||||
|
||||
## Top-Level Bindings
|
||||
|
||||
All top-level bindings are automatically available in template:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// Variables
|
||||
const msg = 'Hello'
|
||||
|
||||
// Imports
|
||||
import { capitalize } from './helpers'
|
||||
import MyComponent from './MyComponent.vue'
|
||||
|
||||
// Functions
|
||||
function greet() {
|
||||
console.log(msg)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MyComponent />
|
||||
<p>{{ capitalize(msg) }}</p>
|
||||
<button @click="greet">Greet</button>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Compiler Macros
|
||||
|
||||
These are available without import:
|
||||
|
||||
- `defineProps()` - declare props
|
||||
- `defineEmits()` - declare emits
|
||||
- `defineModel()` - declare v-model (3.4+)
|
||||
- `defineExpose()` - expose public instance properties
|
||||
- `defineOptions()` - declare component options (3.3+)
|
||||
- `defineSlots()` - type slot props (3.3+)
|
||||
- `withDefaults()` - provide prop defaults
|
||||
|
||||
## Using Components
|
||||
|
||||
Import and use directly without registration:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import MyComponent from './MyComponent.vue'
|
||||
import { MyButton } from './components'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MyComponent />
|
||||
<MyButton />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Dynamic Components
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import Foo from './Foo.vue'
|
||||
import Bar from './Bar.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<component :is="condition ? Foo : Bar" />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Recursive Components
|
||||
|
||||
SFCs can reference themselves by filename:
|
||||
|
||||
```vue
|
||||
<!-- FooBar.vue can use <FooBar/> in its template -->
|
||||
```
|
||||
|
||||
## Custom Directives
|
||||
|
||||
Variables starting with `v` are available as directives:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const vFocus = {
|
||||
mounted: (el: HTMLElement) => el.focus()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-focus />
|
||||
</template>
|
||||
```
|
||||
|
||||
## defineExpose()
|
||||
|
||||
Components are closed by default. Use `defineExpose` to expose properties:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
const publicMethod = () => console.log('called')
|
||||
|
||||
defineExpose({
|
||||
count,
|
||||
publicMethod
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
Parent can access via template ref:
|
||||
|
||||
```ts
|
||||
const childRef = ref()
|
||||
childRef.value.count // accessible
|
||||
childRef.value.publicMethod() // accessible
|
||||
```
|
||||
|
||||
## defineOptions() (3.3+)
|
||||
|
||||
Declare component options without separate `<script>` block:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
defineOptions({
|
||||
inheritAttrs: false,
|
||||
name: 'CustomName'
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## defineSlots() (3.3+)
|
||||
|
||||
Type slot props for IDE support:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const slots = defineSlots<{
|
||||
default(props: { msg: string }): any
|
||||
header(props: { title: string }): any
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## useSlots() & useAttrs()
|
||||
|
||||
Access slots and attrs in script:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useSlots, useAttrs } from 'vue'
|
||||
|
||||
const slots = useSlots()
|
||||
const attrs = useAttrs()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Top-Level await
|
||||
|
||||
Async setup with Suspense:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const data = await fetch('/api/data').then(r => r.json())
|
||||
</script>
|
||||
```
|
||||
|
||||
> Note: Requires `<Suspense>` boundary in parent.
|
||||
|
||||
## Generic Components (TypeScript)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts" generic="T extends string | number">
|
||||
defineProps<{
|
||||
items: T[]
|
||||
selected: T
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
Multiple generics with constraints:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts" generic="T extends Item, U extends string">
|
||||
import type { Item } from './types'
|
||||
|
||||
defineProps<{
|
||||
item: T
|
||||
label: U
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Alongside Normal Script
|
||||
|
||||
For advanced cases like named exports or one-time side effects:
|
||||
|
||||
```vue
|
||||
<script lang="ts">
|
||||
// Runs once when module is imported
|
||||
runSideEffect()
|
||||
|
||||
export const exportedValue = 'hello'
|
||||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
// Runs for each component instance
|
||||
</script>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/api/sfc-script-setup.html
|
||||
-->
|
||||
212
.claude/skills/vue/references/features-template-refs.md
Normal file
212
.claude/skills/vue/references/features-template-refs.md
Normal file
@@ -0,0 +1,212 @@
|
||||
---
|
||||
name: template-refs
|
||||
description: Access DOM elements and child component instances directly
|
||||
---
|
||||
|
||||
# Template Refs
|
||||
|
||||
Template refs provide direct access to DOM elements and child component instances.
|
||||
|
||||
## Basic Usage (3.5+)
|
||||
|
||||
Use `useTemplateRef()` for type-safe refs:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef, onMounted } from 'vue'
|
||||
|
||||
const inputRef = useTemplateRef<HTMLInputElement>('input')
|
||||
|
||||
onMounted(() => {
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="input" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Legacy Approach (Pre-3.5)
|
||||
|
||||
Use a ref with matching name:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const inputRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
onMounted(() => {
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="inputRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Refs in v-for
|
||||
|
||||
Collect multiple refs into an array:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const items = ref([1, 2, 3])
|
||||
const itemRefs = ref<HTMLLIElement[]>([])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul>
|
||||
<li v-for="item in items" ref="itemRefs">
|
||||
{{ item }}
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
```
|
||||
|
||||
> Note: ref array order is not guaranteed to match source array order.
|
||||
|
||||
## Function Refs
|
||||
|
||||
Use a function for full control:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const elements = new Map<number, HTMLElement>()
|
||||
|
||||
function setItemRef(el: HTMLElement | null, id: number) {
|
||||
if (el) {
|
||||
elements.set(id, el)
|
||||
} else {
|
||||
elements.delete(id)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-for="item in items" :ref="(el) => setItemRef(el, item.id)">
|
||||
{{ item.name }}
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Component Refs
|
||||
|
||||
Access child component instance:
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef, onMounted } from 'vue'
|
||||
import Child from './Child.vue'
|
||||
|
||||
type ChildInstance = InstanceType<typeof Child>
|
||||
const childRef = useTemplateRef<ChildInstance>('child')
|
||||
|
||||
onMounted(() => {
|
||||
// Access exposed properties/methods
|
||||
childRef.value?.someMethod()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Child ref="child" />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Exposing Component Properties
|
||||
|
||||
By default, `<script setup>` components are closed. Use `defineExpose`:
|
||||
|
||||
```vue
|
||||
<!-- Child.vue -->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
const increment = () => count.value++
|
||||
|
||||
// Only these are accessible via ref
|
||||
defineExpose({
|
||||
count,
|
||||
increment
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Focus Management
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef } from 'vue'
|
||||
|
||||
const inputRef = useTemplateRef<HTMLInputElement>('input')
|
||||
|
||||
function focusInput() {
|
||||
inputRef.value?.focus()
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### Scroll Control
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef } from 'vue'
|
||||
|
||||
const containerRef = useTemplateRef<HTMLDivElement>('container')
|
||||
|
||||
function scrollToBottom() {
|
||||
const el = containerRef.value
|
||||
if (el) {
|
||||
el.scrollTop = el.scrollHeight
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### Third-Party Library Integration
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef, onMounted, onUnmounted } from 'vue'
|
||||
import Chart from 'chart.js'
|
||||
|
||||
const canvasRef = useTemplateRef<HTMLCanvasElement>('canvas')
|
||||
let chart: Chart | null = null
|
||||
|
||||
onMounted(() => {
|
||||
if (canvasRef.value) {
|
||||
chart = new Chart(canvasRef.value, {
|
||||
// options
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
chart?.destroy()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<canvas ref="canvas"></canvas>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
1. **Refs are null before mount** - access in `onMounted` or later
|
||||
2. **Conditional refs can be null** - elements with `v-if` may not exist
|
||||
3. **Use optional chaining** - `ref.value?.method()` for safety
|
||||
4. **Avoid overusing** - prefer declarative approaches when possible
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/essentials/template-refs.html
|
||||
- https://vuejs.org/guide/typescript/composition-api.html#typing-template-refs
|
||||
-->
|
||||
274
.claude/skills/vue/references/features-typescript.md
Normal file
274
.claude/skills/vue/references/features-typescript.md
Normal file
@@ -0,0 +1,274 @@
|
||||
---
|
||||
name: typescript-integration
|
||||
description: Type Vue components with TypeScript in Composition API
|
||||
---
|
||||
|
||||
# TypeScript with Vue
|
||||
|
||||
Vue provides excellent TypeScript support in Composition API.
|
||||
|
||||
## Typing Props
|
||||
|
||||
### Type-based declaration (recommended)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
title: string
|
||||
count?: number
|
||||
items: string[]
|
||||
user: { name: string; age: number }
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
```
|
||||
|
||||
### With defaults (3.5+)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
msg?: string
|
||||
labels?: string[]
|
||||
}
|
||||
|
||||
const { msg = 'hello', labels = ['one'] } = defineProps<Props>()
|
||||
```
|
||||
|
||||
### With withDefaults (3.4 and below)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
msg?: string
|
||||
labels?: string[]
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
msg: 'hello',
|
||||
labels: () => ['one', 'two']
|
||||
})
|
||||
```
|
||||
|
||||
### Complex prop types
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
interface Book {
|
||||
title: string
|
||||
author: string
|
||||
year: number
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
book: Book
|
||||
callback: (id: number) => void
|
||||
}>()
|
||||
```
|
||||
|
||||
## Typing Emits
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// Call signature syntax
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', id: number): void
|
||||
(e: 'update', value: string): void
|
||||
}>()
|
||||
|
||||
// Named tuple syntax (3.3+, more concise)
|
||||
const emit = defineEmits<{
|
||||
change: [id: number]
|
||||
update: [value: string]
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Typing ref()
|
||||
|
||||
```ts
|
||||
import { ref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
// Inferred
|
||||
const count = ref(0) // Ref<number>
|
||||
|
||||
// Explicit generic
|
||||
const name = ref<string>() // Ref<string | undefined>
|
||||
|
||||
// Type annotation
|
||||
const id: Ref<string | number> = ref('abc')
|
||||
```
|
||||
|
||||
## Typing reactive()
|
||||
|
||||
```ts
|
||||
import { reactive } from 'vue'
|
||||
|
||||
interface State {
|
||||
count: number
|
||||
name: string
|
||||
}
|
||||
|
||||
// Use interface on variable
|
||||
const state: State = reactive({
|
||||
count: 0,
|
||||
name: 'Vue'
|
||||
})
|
||||
```
|
||||
|
||||
## Typing computed()
|
||||
|
||||
```ts
|
||||
import { computed } from 'vue'
|
||||
|
||||
// Inferred from getter
|
||||
const double = computed(() => count.value * 2) // ComputedRef<number>
|
||||
|
||||
// Explicit generic
|
||||
const result = computed<string>(() => {
|
||||
return String(value.value)
|
||||
})
|
||||
```
|
||||
|
||||
## Typing Event Handlers
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
function handleChange(event: Event) {
|
||||
const target = event.target as HTMLInputElement
|
||||
console.log(target.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input @change="handleChange" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Typing Template Refs
|
||||
|
||||
### useTemplateRef (3.5+)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef, onMounted } from 'vue'
|
||||
|
||||
const inputRef = useTemplateRef<HTMLInputElement>('input')
|
||||
|
||||
onMounted(() => {
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="input" />
|
||||
</template>
|
||||
```
|
||||
|
||||
### Legacy ref approach
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
const inputRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
onMounted(() => {
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input ref="inputRef" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Typing Component Refs
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useTemplateRef } from 'vue'
|
||||
import MyComponent from './MyComponent.vue'
|
||||
|
||||
type MyComponentInstance = InstanceType<typeof MyComponent>
|
||||
const compRef = useTemplateRef<MyComponentInstance>('comp')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MyComponent ref="comp" />
|
||||
</template>
|
||||
```
|
||||
|
||||
## Typing Provide/Inject
|
||||
|
||||
```ts
|
||||
import { provide, inject } from 'vue'
|
||||
import type { InjectionKey, Ref } from 'vue'
|
||||
|
||||
// Define typed key
|
||||
const countKey = Symbol() as InjectionKey<Ref<number>>
|
||||
|
||||
// Provider
|
||||
provide(countKey, ref(0))
|
||||
|
||||
// Injector
|
||||
const count = inject(countKey) // Ref<number> | undefined
|
||||
|
||||
// With default
|
||||
const count = inject(countKey, ref(0)) // Ref<number>
|
||||
|
||||
// String key with explicit type
|
||||
const foo = inject<string>('foo')
|
||||
```
|
||||
|
||||
## Typing defineModel (3.4+)
|
||||
|
||||
```ts
|
||||
// Basic
|
||||
const model = defineModel<string>()
|
||||
// ^? Ref<string | undefined>
|
||||
|
||||
// Required
|
||||
const model = defineModel<string>({ required: true })
|
||||
// ^? Ref<string>
|
||||
|
||||
// With modifiers
|
||||
const [model, modifiers] = defineModel<string, 'trim' | 'uppercase'>()
|
||||
// ^? Record<'trim' | 'uppercase', true | undefined>
|
||||
```
|
||||
|
||||
## Global Custom Properties
|
||||
|
||||
Extend `ComponentCustomProperties` for global properties:
|
||||
|
||||
```ts
|
||||
// types/vue.d.ts
|
||||
declare module 'vue' {
|
||||
interface ComponentCustomProperties {
|
||||
$http: typeof axios
|
||||
$translate: (key: string) => string
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Generic Components
|
||||
|
||||
```vue
|
||||
<script setup lang="ts" generic="T">
|
||||
defineProps<{
|
||||
items: T[]
|
||||
selected: T
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
select: [item: T]
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
<!--
|
||||
Source references:
|
||||
- https://vuejs.org/guide/typescript/composition-api.html
|
||||
- https://vuejs.org/guide/typescript/overview.html
|
||||
-->
|
||||
21
.claude/skills/vueuse-functions/LICENSE.md
Normal file
21
.claude/skills/vueuse-functions/LICENSE.md
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 SerKo <https://github.com/serkodev>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
418
.claude/skills/vueuse-functions/SKILL.md
Normal file
418
.claude/skills/vueuse-functions/SKILL.md
Normal file
@@ -0,0 +1,418 @@
|
||||
---
|
||||
name: vueuse-functions
|
||||
description: Apply VueUse composables where appropriate to build concise, maintainable Vue.js / Nuxt features.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: SerKo <https://github.com/serkodev>
|
||||
version: "1.1"
|
||||
compatibility: Requires Vue 3 (or above) or Nuxt 3 (or above) project
|
||||
---
|
||||
|
||||
# VueUse Functions
|
||||
|
||||
This skill is a decision-and-implementation guide for VueUse composables in Vue.js / Nuxt projects. It maps requirements to the most suitable VueUse function, applies the correct usage pattern, and prefers composable-based solutions over bespoke code to keep implementations concise, maintainable, and performant.
|
||||
|
||||
## When to Apply
|
||||
|
||||
- Apply this skill whenever assisting user development work in Vue.js / Nuxt.
|
||||
- Always check first whether a VueUse function can implement the requirement.
|
||||
- Prefer VueUse composables over custom code to improve readability, maintainability, and performance.
|
||||
- Map requirements to the most appropriate VueUse function and follow the function’s invocation rule.
|
||||
- Please refer to the `Invocation` field in the below functions table. For example:
|
||||
- `AUTO`: Use automatically when applicable.
|
||||
- `EXTERNAL`: Use only if the user already installed the required external dependency; otherwise reconsider, and ask to install only if truly needed.
|
||||
- `EXPLICIT_ONLY`: Use only when explicitly requested by the user.
|
||||
> *NOTE* User instructions in the prompt or `AGENTS.md` may override a function’s default `Invocation` rule.
|
||||
|
||||
## Functions
|
||||
|
||||
All functions listed below are part of the [VueUse](https://vueuse.org/) library, each section categorizes functions based on their functionality.
|
||||
|
||||
IMPORTANT: Each function entry includes a short `Description` and a detailed `Reference`. When using any function, always consult the corresponding document in `./references` for Usage details and Type Declarations.
|
||||
|
||||
### State
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`createGlobalState`](references/createGlobalState.md) | Keep states in the global scope to be reusable across Vue instances | AUTO |
|
||||
| [`createInjectionState`](references/createInjectionState.md) | Create global state that can be injected into components | AUTO |
|
||||
| [`createSharedComposable`](references/createSharedComposable.md) | Make a composable function usable with multiple Vue instances | AUTO |
|
||||
| [`injectLocal`](references/injectLocal.md) | Extended `inject` with ability to call `provideLocal` to provide the value in the same component | AUTO |
|
||||
| [`provideLocal`](references/provideLocal.md) | Extended `provide` with ability to call `injectLocal` to obtain the value in the same component | AUTO |
|
||||
| [`useAsyncState`](references/useAsyncState.md) | Reactive async state | AUTO |
|
||||
| [`useDebouncedRefHistory`](references/useDebouncedRefHistory.md) | Shorthand for `useRefHistory` with debounced filter | AUTO |
|
||||
| [`useLastChanged`](references/useLastChanged.md) | Records the timestamp of the last change | AUTO |
|
||||
| [`useLocalStorage`](references/useLocalStorage.md) | Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) | AUTO |
|
||||
| [`useManualRefHistory`](references/useManualRefHistory.md) | Manually track the change history of a ref when the using calls `commit()` | AUTO |
|
||||
| [`useRefHistory`](references/useRefHistory.md) | Track the change history of a ref | AUTO |
|
||||
| [`useSessionStorage`](references/useSessionStorage.md) | Reactive [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) | AUTO |
|
||||
| [`useStorage`](references/useStorage.md) | Create a reactive ref that can be used to access & modify [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) or [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) | AUTO |
|
||||
| [`useStorageAsync`](references/useStorageAsync.md) | Reactive Storage in with async support | AUTO |
|
||||
| [`useThrottledRefHistory`](references/useThrottledRefHistory.md) | Shorthand for `useRefHistory` with throttled filter | AUTO |
|
||||
|
||||
### Elements
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useActiveElement`](references/useActiveElement.md) | Reactive `document.activeElement` | AUTO |
|
||||
| [`useDocumentVisibility`](references/useDocumentVisibility.md) | Reactively track [`document.visibilityState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState) | AUTO |
|
||||
| [`useDraggable`](references/useDraggable.md) | Make elements draggable | AUTO |
|
||||
| [`useDropZone`](references/useDropZone.md) | Create a zone where files can be dropped | AUTO |
|
||||
| [`useElementBounding`](references/useElementBounding.md) | Reactive [bounding box](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of an HTML element | AUTO |
|
||||
| [`useElementSize`](references/useElementSize.md) | Reactive size of an HTML element | AUTO |
|
||||
| [`useElementVisibility`](references/useElementVisibility.md) | Tracks the visibility of an element within the viewport | AUTO |
|
||||
| [`useIntersectionObserver`](references/useIntersectionObserver.md) | Detects that a target element's visibility | AUTO |
|
||||
| [`useMouseInElement`](references/useMouseInElement.md) | Reactive mouse position related to an element | AUTO |
|
||||
| [`useMutationObserver`](references/useMutationObserver.md) | Watch for changes being made to the DOM tree | AUTO |
|
||||
| [`useParentElement`](references/useParentElement.md) | Get parent element of the given element | AUTO |
|
||||
| [`useResizeObserver`](references/useResizeObserver.md) | Reports changes to the dimensions of an Element's content or the border-box | AUTO |
|
||||
| [`useWindowFocus`](references/useWindowFocus.md) | Reactively track window focus with `window.onfocus` and `window.onblur` events | AUTO |
|
||||
| [`useWindowScroll`](references/useWindowScroll.md) | Reactive window scroll | AUTO |
|
||||
| [`useWindowSize`](references/useWindowSize.md) | Reactive window size | AUTO |
|
||||
|
||||
### Browser
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useBluetooth`](references/useBluetooth.md) | Reactive [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API) | AUTO |
|
||||
| [`useBreakpoints`](references/useBreakpoints.md) | Reactive viewport breakpoints | AUTO |
|
||||
| [`useBroadcastChannel`](references/useBroadcastChannel.md) | Reactive [BroadcastChannel API](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel) | AUTO |
|
||||
| [`useBrowserLocation`](references/useBrowserLocation.md) | Reactive browser location | AUTO |
|
||||
| [`useClipboard`](references/useClipboard.md) | Reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) | AUTO |
|
||||
| [`useClipboardItems`](references/useClipboardItems.md) | Reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) | AUTO |
|
||||
| [`useColorMode`](references/useColorMode.md) | Reactive color mode (dark / light / customs) with auto data persistence | AUTO |
|
||||
| [`useCssVar`](references/useCssVar.md) | Manipulate CSS variables | AUTO |
|
||||
| [`useDark`](references/useDark.md) | Reactive dark mode with auto data persistence | AUTO |
|
||||
| [`useEventListener`](references/useEventListener.md) | Use EventListener with ease | AUTO |
|
||||
| [`useEyeDropper`](references/useEyeDropper.md) | Reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API) | AUTO |
|
||||
| [`useFavicon`](references/useFavicon.md) | Reactive favicon | AUTO |
|
||||
| [`useFileDialog`](references/useFileDialog.md) | Open file dialog with ease | AUTO |
|
||||
| [`useFileSystemAccess`](references/useFileSystemAccess.md) | Create and read and write local files with [FileSystemAccessAPI](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API) | AUTO |
|
||||
| [`useFullscreen`](references/useFullscreen.md) | Reactive [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) | AUTO |
|
||||
| [`useGamepad`](references/useGamepad.md) | Provides reactive bindings for the [Gamepad API](https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API) | AUTO |
|
||||
| [`useImage`](references/useImage.md) | Reactive load an image in the browser | AUTO |
|
||||
| [`useMediaControls`](references/useMediaControls.md) | Reactive media controls for both `audio` and `video` elements | AUTO |
|
||||
| [`useMediaQuery`](references/useMediaQuery.md) | Reactive [Media Query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries) | AUTO |
|
||||
| [`useMemory`](references/useMemory.md) | Reactive Memory Info | AUTO |
|
||||
| [`useObjectUrl`](references/useObjectUrl.md) | Reactive URL representing an object | AUTO |
|
||||
| [`usePerformanceObserver`](references/usePerformanceObserver.md) | Observe performance metrics | AUTO |
|
||||
| [`usePermission`](references/usePermission.md) | Reactive [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API) | AUTO |
|
||||
| [`usePreferredColorScheme`](references/usePreferredColorScheme.md) | Reactive [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query | AUTO |
|
||||
| [`usePreferredContrast`](references/usePreferredContrast.md) | Reactive [prefers-contrast](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast) media query | AUTO |
|
||||
| [`usePreferredDark`](references/usePreferredDark.md) | Reactive dark theme preference | AUTO |
|
||||
| [`usePreferredLanguages`](references/usePreferredLanguages.md) | Reactive [Navigator Languages](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages) | AUTO |
|
||||
| [`usePreferredReducedMotion`](references/usePreferredReducedMotion.md) | Reactive [prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) media query | AUTO |
|
||||
| [`usePreferredReducedTransparency`](references/usePreferredReducedTransparency.md) | Reactive [prefers-reduced-transparency](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-transparency) media query | AUTO |
|
||||
| [`useScreenOrientation`](references/useScreenOrientation.md) | Reactive [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API) | AUTO |
|
||||
| [`useScreenSafeArea`](references/useScreenSafeArea.md) | Reactive `env(safe-area-inset-*)` | AUTO |
|
||||
| [`useScriptTag`](references/useScriptTag.md) | Creates a script tag | AUTO |
|
||||
| [`useShare`](references/useShare.md) | Reactive [Web Share API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share) | AUTO |
|
||||
| [`useSSRWidth`](references/useSSRWidth.md) | Used to set a global viewport width which will be used when rendering SSR components that rely on the viewport width like [`useMediaQuery`](../useMediaQuery/index.md) or [`useBreakpoints`](../useBreakpoints/index.md) | AUTO |
|
||||
| [`useStyleTag`](references/useStyleTag.md) | Inject reactive `style` element in head | AUTO |
|
||||
| [`useTextareaAutosize`](references/useTextareaAutosize.md) | Automatically update the height of a textarea depending on the content | AUTO |
|
||||
| [`useTextDirection`](references/useTextDirection.md) | Reactive [dir](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir) of the element's text | AUTO |
|
||||
| [`useTitle`](references/useTitle.md) | Reactive document title | AUTO |
|
||||
| [`useUrlSearchParams`](references/useUrlSearchParams.md) | Reactive [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) | AUTO |
|
||||
| [`useVibrate`](references/useVibrate.md) | Reactive [Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API) | AUTO |
|
||||
| [`useWakeLock`](references/useWakeLock.md) | Reactive [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API) | AUTO |
|
||||
| [`useWebNotification`](references/useWebNotification.md) | Reactive [Notification](https://developer.mozilla.org/en-US/docs/Web/API/notification) | AUTO |
|
||||
| [`useWebWorker`](references/useWebWorker.md) | Simple [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) registration and communication | AUTO |
|
||||
| [`useWebWorkerFn`](references/useWebWorkerFn.md) | Run expensive functions without blocking the UI | AUTO |
|
||||
|
||||
### Sensors
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`onClickOutside`](references/onClickOutside.md) | Listen for clicks outside of an element | AUTO |
|
||||
| [`onElementRemoval`](references/onElementRemoval.md) | Fires when the element or any element containing it is removed | AUTO |
|
||||
| [`onKeyStroke`](references/onKeyStroke.md) | Listen for keyboard keystrokes | AUTO |
|
||||
| [`onLongPress`](references/onLongPress.md) | Listen for a long press on an element | AUTO |
|
||||
| [`onStartTyping`](references/onStartTyping.md) | Fires when users start typing on non-editable elements | AUTO |
|
||||
| [`useBattery`](references/useBattery.md) | Reactive [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) | AUTO |
|
||||
| [`useDeviceMotion`](references/useDeviceMotion.md) | Reactive [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent) | AUTO |
|
||||
| [`useDeviceOrientation`](references/useDeviceOrientation.md) | Reactive [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent) | AUTO |
|
||||
| [`useDevicePixelRatio`](references/useDevicePixelRatio.md) | Reactively track [`window.devicePixelRatio`](https://developer.mozilla.org/docs/Web/API/Window/devicePixelRatio) | AUTO |
|
||||
| [`useDevicesList`](references/useDevicesList.md) | Reactive [enumerateDevices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) listing available input/output devices | AUTO |
|
||||
| [`useDisplayMedia`](references/useDisplayMedia.md) | Reactive [`mediaDevices.getDisplayMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) streaming | AUTO |
|
||||
| [`useElementByPoint`](references/useElementByPoint.md) | Reactive element by point | AUTO |
|
||||
| [`useElementHover`](references/useElementHover.md) | Reactive element's hover state | AUTO |
|
||||
| [`useFocus`](references/useFocus.md) | Reactive utility to track or set the focus state of a DOM element | AUTO |
|
||||
| [`useFocusWithin`](references/useFocusWithin.md) | Reactive utility to track if an element or one of its decendants has focus | AUTO |
|
||||
| [`useFps`](references/useFps.md) | Reactive FPS (frames per second) | AUTO |
|
||||
| [`useGeolocation`](references/useGeolocation.md) | Reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) | AUTO |
|
||||
| [`useIdle`](references/useIdle.md) | Tracks whether the user is being inactive | AUTO |
|
||||
| [`useInfiniteScroll`](references/useInfiniteScroll.md) | Infinite scrolling of the element | AUTO |
|
||||
| [`useKeyModifier`](references/useKeyModifier.md) | Reactive [Modifier State](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState) | AUTO |
|
||||
| [`useMagicKeys`](references/useMagicKeys.md) | Reactive keys pressed state | AUTO |
|
||||
| [`useMouse`](references/useMouse.md) | Reactive mouse position | AUTO |
|
||||
| [`useMousePressed`](references/useMousePressed.md) | Reactive mouse pressing state | AUTO |
|
||||
| [`useNavigatorLanguage`](references/useNavigatorLanguage.md) | Reactive [navigator.language](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) | AUTO |
|
||||
| [`useNetwork`](references/useNetwork.md) | Reactive [Network status](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) | AUTO |
|
||||
| [`useOnline`](references/useOnline.md) | Reactive online state | AUTO |
|
||||
| [`usePageLeave`](references/usePageLeave.md) | Reactive state to show whether the mouse leaves the page | AUTO |
|
||||
| [`useParallax`](references/useParallax.md) | Create parallax effect easily | AUTO |
|
||||
| [`usePointer`](references/usePointer.md) | Reactive [pointer state](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) | AUTO |
|
||||
| [`usePointerLock`](references/usePointerLock.md) | Reactive [pointer lock](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) | AUTO |
|
||||
| [`usePointerSwipe`](references/usePointerSwipe.md) | Reactive swipe detection based on [PointerEvents](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent) | AUTO |
|
||||
| [`useScroll`](references/useScroll.md) | Reactive scroll position and state | AUTO |
|
||||
| [`useScrollLock`](references/useScrollLock.md) | Lock scrolling of the element | AUTO |
|
||||
| [`useSpeechRecognition`](references/useSpeechRecognition.md) | Reactive [SpeechRecognition](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition) | AUTO |
|
||||
| [`useSpeechSynthesis`](references/useSpeechSynthesis.md) | Reactive [SpeechSynthesis](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis) | AUTO |
|
||||
| [`useSwipe`](references/useSwipe.md) | Reactive swipe detection based on [`TouchEvents`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent) | AUTO |
|
||||
| [`useTextSelection`](references/useTextSelection.md) | Reactively track user text selection based on [`Window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection) | AUTO |
|
||||
| [`useUserMedia`](references/useUserMedia.md) | Reactive [`mediaDevices.getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) streaming | AUTO |
|
||||
|
||||
### Network
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useEventSource`](references/useEventSource.md) | An [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or [Server-Sent-Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) instance opens a persistent connection to an HTTP server | AUTO |
|
||||
| [`useFetch`](references/useFetch.md) | Reactive [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the ability to abort requests | AUTO |
|
||||
| [`useWebSocket`](references/useWebSocket.md) | Reactive [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) client | AUTO |
|
||||
|
||||
### Animation
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useAnimate`](references/useAnimate.md) | Reactive [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) | AUTO |
|
||||
| [`useInterval`](references/useInterval.md) | Reactive counter increases on every interval | AUTO |
|
||||
| [`useIntervalFn`](references/useIntervalFn.md) | Wrapper for `setInterval` with controls | AUTO |
|
||||
| [`useNow`](references/useNow.md) | Reactive current Date instance | AUTO |
|
||||
| [`useRafFn`](references/useRafFn.md) | Call function on every `requestAnimationFrame` | AUTO |
|
||||
| [`useTimeout`](references/useTimeout.md) | Update value after a given time with controls | AUTO |
|
||||
| [`useTimeoutFn`](references/useTimeoutFn.md) | Wrapper for `setTimeout` with controls | AUTO |
|
||||
| [`useTimestamp`](references/useTimestamp.md) | Reactive current timestamp | AUTO |
|
||||
| [`useTransition`](references/useTransition.md) | Transition between values | AUTO |
|
||||
|
||||
### Component
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`computedInject`](references/computedInject.md) | Combine computed and inject | AUTO |
|
||||
| [`createReusableTemplate`](references/createReusableTemplate.md) | Define and reuse template inside the component scope | AUTO |
|
||||
| [`createTemplatePromise`](references/createTemplatePromise.md) | Template as Promise | AUTO |
|
||||
| [`templateRef`](references/templateRef.md) | Shorthand for binding ref to template element | AUTO |
|
||||
| [`tryOnBeforeMount`](references/tryOnBeforeMount.md) | Safe `onBeforeMount` | AUTO |
|
||||
| [`tryOnBeforeUnmount`](references/tryOnBeforeUnmount.md) | Safe `onBeforeUnmount` | AUTO |
|
||||
| [`tryOnMounted`](references/tryOnMounted.md) | Safe `onMounted` | AUTO |
|
||||
| [`tryOnScopeDispose`](references/tryOnScopeDispose.md) | Safe `onScopeDispose` | AUTO |
|
||||
| [`tryOnUnmounted`](references/tryOnUnmounted.md) | Safe `onUnmounted` | AUTO |
|
||||
| [`unrefElement`](references/unrefElement.md) | Retrieves the underlying DOM element from a Vue ref or component instance | AUTO |
|
||||
| [`useCurrentElement`](references/useCurrentElement.md) | Get the DOM element of current component as a ref | AUTO |
|
||||
| [`useMounted`](references/useMounted.md) | Mounted state in ref | AUTO |
|
||||
| [`useTemplateRefsList`](references/useTemplateRefsList.md) | Shorthand for binding refs to template elements and components inside `v-for` | AUTO |
|
||||
| [`useVirtualList`](references/useVirtualList.md) | Create virtual lists with ease | AUTO |
|
||||
| [`useVModel`](references/useVModel.md) | Shorthand for v-model binding | AUTO |
|
||||
| [`useVModels`](references/useVModels.md) | Shorthand for props v-model binding | AUTO |
|
||||
|
||||
### Watch
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`until`](references/until.md) | Promised one-time watch for changes | AUTO |
|
||||
| [`watchArray`](references/watchArray.md) | Watch for an array with additions and removals | AUTO |
|
||||
| [`watchAtMost`](references/watchAtMost.md) | `watch` with the number of times triggered | AUTO |
|
||||
| [`watchDebounced`](references/watchDebounced.md) | Debounced watch | AUTO |
|
||||
| [`watchDeep`](references/watchDeep.md) | Shorthand for watching value with `{deep: true}` | AUTO |
|
||||
| [`watchIgnorable`](references/watchIgnorable.md) | Ignorable watch | AUTO |
|
||||
| [`watchImmediate`](references/watchImmediate.md) | Shorthand for watching value with `{immediate: true}` | AUTO |
|
||||
| [`watchOnce`](references/watchOnce.md) | Shorthand for watching value with `{ once: true }` | AUTO |
|
||||
| [`watchPausable`](references/watchPausable.md) | Pausable watch | AUTO |
|
||||
| [`watchThrottled`](references/watchThrottled.md) | Throttled watch | AUTO |
|
||||
| [`watchTriggerable`](references/watchTriggerable.md) | Watch that can be triggered manually | AUTO |
|
||||
| [`watchWithFilter`](references/watchWithFilter.md) | `watch` with additional EventFilter control | AUTO |
|
||||
| [`whenever`](references/whenever.md) | Shorthand for watching value to be truthy | AUTO |
|
||||
|
||||
### Reactivity
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`computedAsync`](references/computedAsync.md) | Computed for async functions | AUTO |
|
||||
| [`computedEager`](references/computedEager.md) | Eager computed without lazy evaluation | AUTO |
|
||||
| [`computedWithControl`](references/computedWithControl.md) | Explicitly define the dependencies of computed | AUTO |
|
||||
| [`createRef`](references/createRef.md) | Returns a `deepRef` or `shallowRef` depending on the `deep` param | AUTO |
|
||||
| [`extendRef`](references/extendRef.md) | Add extra attributes to Ref | AUTO |
|
||||
| [`reactify`](references/reactify.md) | Converts plain functions into reactive functions | AUTO |
|
||||
| [`reactifyObject`](references/reactifyObject.md) | Apply `reactify` to an object | AUTO |
|
||||
| [`reactiveComputed`](references/reactiveComputed.md) | Computed reactive object | AUTO |
|
||||
| [`reactiveOmit`](references/reactiveOmit.md) | Reactively omit fields from a reactive object | AUTO |
|
||||
| [`reactivePick`](references/reactivePick.md) | Reactively pick fields from a reactive object | AUTO |
|
||||
| [`refAutoReset`](references/refAutoReset.md) | A ref which will be reset to the default value after some time | AUTO |
|
||||
| [`refDebounced`](references/refDebounced.md) | Debounce execution of a ref value | AUTO |
|
||||
| [`refDefault`](references/refDefault.md) | Apply default value to a ref | AUTO |
|
||||
| [`refManualReset`](references/refManualReset.md) | Create a ref with manual reset functionality | AUTO |
|
||||
| [`refThrottled`](references/refThrottled.md) | Throttle changing of a ref value | AUTO |
|
||||
| [`refWithControl`](references/refWithControl.md) | Fine-grained controls over ref and its reactivity | AUTO |
|
||||
| [`syncRef`](references/syncRef.md) | Two-way refs synchronization | AUTO |
|
||||
| [`syncRefs`](references/syncRefs.md) | Keep target refs in sync with a source ref | AUTO |
|
||||
| [`toReactive`](references/toReactive.md) | Converts ref to reactive | AUTO |
|
||||
| [`toRef`](references/toRef.md) | Normalize value/ref/getter to `ref` or `computed` | EXPLICIT_ONLY |
|
||||
| [`toRefs`](references/toRefs.md) | Extended [`toRefs`](https://vuejs.org/api/reactivity-utilities.html#torefs) that also accepts refs of an object | AUTO |
|
||||
|
||||
### Array
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useArrayDifference`](references/useArrayDifference.md) | Reactive get array difference of two arrays | AUTO |
|
||||
| [`useArrayEvery`](references/useArrayEvery.md) | Reactive `Array.every` | AUTO |
|
||||
| [`useArrayFilter`](references/useArrayFilter.md) | Reactive `Array.filter` | AUTO |
|
||||
| [`useArrayFind`](references/useArrayFind.md) | Reactive `Array.find` | AUTO |
|
||||
| [`useArrayFindIndex`](references/useArrayFindIndex.md) | Reactive `Array.findIndex` | AUTO |
|
||||
| [`useArrayFindLast`](references/useArrayFindLast.md) | Reactive `Array.findLast` | AUTO |
|
||||
| [`useArrayIncludes`](references/useArrayIncludes.md) | Reactive `Array.includes` | AUTO |
|
||||
| [`useArrayJoin`](references/useArrayJoin.md) | Reactive `Array.join` | AUTO |
|
||||
| [`useArrayMap`](references/useArrayMap.md) | Reactive `Array.map` | AUTO |
|
||||
| [`useArrayReduce`](references/useArrayReduce.md) | Reactive `Array.reduce` | AUTO |
|
||||
| [`useArraySome`](references/useArraySome.md) | Reactive `Array.some` | AUTO |
|
||||
| [`useArrayUnique`](references/useArrayUnique.md) | Reactive unique array | AUTO |
|
||||
| [`useSorted`](references/useSorted.md) | Reactive sort array | AUTO |
|
||||
|
||||
### Time
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useCountdown`](references/useCountdown.md) | Wrapper for `useIntervalFn` that provides a countdown timer | AUTO |
|
||||
| [`useDateFormat`](references/useDateFormat.md) | Get the formatted date according to the string of tokens passed in | AUTO |
|
||||
| [`useTimeAgo`](references/useTimeAgo.md) | Reactive time ago | AUTO |
|
||||
| [`useTimeAgoIntl`](references/useTimeAgoIntl.md) | Reactive time ago with i18n supported | AUTO |
|
||||
|
||||
### Utilities
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`createEventHook`](references/createEventHook.md) | Utility for creating event hooks | AUTO |
|
||||
| [`createUnrefFn`](references/createUnrefFn.md) | Make a plain function accepting ref and raw values as arguments | AUTO |
|
||||
| [`get`](references/get.md) | Shorthand for accessing `ref.value` | EXPLICIT_ONLY |
|
||||
| [`isDefined`](references/isDefined.md) | Non-nullish checking type guard for Ref | AUTO |
|
||||
| [`makeDestructurable`](references/makeDestructurable.md) | Make isomorphic destructurable for object and array at the same time | AUTO |
|
||||
| [`set`](references/set.md) | Shorthand for `ref.value = x` | EXPLICIT_ONLY |
|
||||
| [`useAsyncQueue`](references/useAsyncQueue.md) | Executes each asynchronous task sequentially and passes the current task result to the next task | AUTO |
|
||||
| [`useBase64`](references/useBase64.md) | Reactive base64 transforming | AUTO |
|
||||
| [`useCached`](references/useCached.md) | Cache a ref with a custom comparator | AUTO |
|
||||
| [`useCloned`](references/useCloned.md) | Reactive clone of a ref | AUTO |
|
||||
| [`useConfirmDialog`](references/useConfirmDialog.md) | Creates event hooks to support modals and confirmation dialog chains | AUTO |
|
||||
| [`useCounter`](references/useCounter.md) | Basic counter with utility functions | AUTO |
|
||||
| [`useCycleList`](references/useCycleList.md) | Cycle through a list of items | AUTO |
|
||||
| [`useDebounceFn`](references/useDebounceFn.md) | Debounce execution of a function | AUTO |
|
||||
| [`useEventBus`](references/useEventBus.md) | A basic event bus | AUTO |
|
||||
| [`useMemoize`](references/useMemoize.md) | Cache results of functions depending on arguments and keep it reactive | AUTO |
|
||||
| [`useOffsetPagination`](references/useOffsetPagination.md) | Reactive offset pagination | AUTO |
|
||||
| [`usePrevious`](references/usePrevious.md) | Holds the previous value of a ref | AUTO |
|
||||
| [`useStepper`](references/useStepper.md) | Provides helpers for building a multi-step wizard interface | AUTO |
|
||||
| [`useSupported`](references/useSupported.md) | SSR compatibility `isSupported` | AUTO |
|
||||
| [`useThrottleFn`](references/useThrottleFn.md) | Throttle execution of a function | AUTO |
|
||||
| [`useTimeoutPoll`](references/useTimeoutPoll.md) | Use timeout to poll something | AUTO |
|
||||
| [`useToggle`](references/useToggle.md) | A boolean switcher with utility functions | AUTO |
|
||||
| [`useToNumber`](references/useToNumber.md) | Reactively convert a string ref to number | AUTO |
|
||||
| [`useToString`](references/useToString.md) | Reactively convert a ref to string | AUTO |
|
||||
|
||||
### @Electron
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useIpcRenderer`](references/useIpcRenderer.md) | Provides [ipcRenderer](https://www.electronjs.org/docs/api/ipc-renderer) and all of its APIs | EXTERNAL |
|
||||
| [`useIpcRendererInvoke`](references/useIpcRendererInvoke.md) | Reactive [ipcRenderer.invoke API](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args) result | EXTERNAL |
|
||||
| [`useIpcRendererOn`](references/useIpcRendererOn.md) | Use [ipcRenderer.on](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener) with ease and [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted | EXTERNAL |
|
||||
| [`useZoomFactor`](references/useZoomFactor.md) | Reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom factor | EXTERNAL |
|
||||
| [`useZoomLevel`](references/useZoomLevel.md) | Reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom level | EXTERNAL |
|
||||
|
||||
### @Firebase
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useAuth`](references/useAuth.md) | Reactive [Firebase Auth](https://firebase.google.com/docs/auth) binding | EXTERNAL |
|
||||
| [`useFirestore`](references/useFirestore.md) | Reactive [Firestore](https://firebase.google.com/docs/firestore) binding | EXTERNAL |
|
||||
| [`useRTDB`](references/useRTDB.md) | Reactive [Firebase Realtime Database](https://firebase.google.com/docs/database) binding | EXTERNAL |
|
||||
|
||||
### @Head
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`createHead`](https://github.com/vueuse/head#api) | Create the head manager instance. | EXTERNAL |
|
||||
| [`useHead`](https://github.com/vueuse/head#api) | Update head meta tags reactively. | EXTERNAL |
|
||||
|
||||
### @Integrations
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useAsyncValidator`](references/useAsyncValidator.md) | Wrapper for [`async-validator`](https://github.com/yiminghe/async-validator) | EXTERNAL |
|
||||
| [`useAxios`](references/useAxios.md) | Wrapper for [`axios`](https://github.com/axios/axios) | EXTERNAL |
|
||||
| [`useChangeCase`](references/useChangeCase.md) | Reactive wrapper for [`change-case`](https://github.com/blakeembrey/change-case) | EXTERNAL |
|
||||
| [`useCookies`](references/useCookies.md) | Wrapper for [`universal-cookie`](https://www.npmjs.com/package/universal-cookie) | EXTERNAL |
|
||||
| [`useDrauu`](references/useDrauu.md) | Reactive instance for [drauu](https://github.com/antfu/drauu) | EXTERNAL |
|
||||
| [`useFocusTrap`](references/useFocusTrap.md) | Reactive wrapper for [`focus-trap`](https://github.com/focus-trap/focus-trap) | EXTERNAL |
|
||||
| [`useFuse`](references/useFuse.md) | Easily implement fuzzy search using a composable with [Fuse.js](https://github.com/krisk/fuse) | EXTERNAL |
|
||||
| [`useIDBKeyval`](references/useIDBKeyval.md) | Wrapper for [`idb-keyval`](https://www.npmjs.com/package/idb-keyval) | EXTERNAL |
|
||||
| [`useJwt`](references/useJwt.md) | Wrapper for [`jwt-decode`](https://github.com/auth0/jwt-decode) | EXTERNAL |
|
||||
| [`useNProgress`](references/useNProgress.md) | Reactive wrapper for [`nprogress`](https://github.com/rstacruz/nprogress) | EXTERNAL |
|
||||
| [`useQRCode`](references/useQRCode.md) | Wrapper for [`qrcode`](https://github.com/soldair/node-qrcode) | EXTERNAL |
|
||||
| [`useSortable`](references/useSortable.md) | Wrapper for [`sortable`](https://github.com/SortableJS/Sortable) | EXTERNAL |
|
||||
|
||||
### @Math
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`createGenericProjection`](references/createGenericProjection.md) | Generic version of `createProjection` | EXTERNAL |
|
||||
| [`createProjection`](references/createProjection.md) | Reactive numeric projection from one domain to another | EXTERNAL |
|
||||
| [`logicAnd`](references/logicAnd.md) | `AND` condition for refs | EXTERNAL |
|
||||
| [`logicNot`](references/logicNot.md) | `NOT` condition for ref | EXTERNAL |
|
||||
| [`logicOr`](references/logicOr.md) | `OR` conditions for refs | EXTERNAL |
|
||||
| [`useAbs`](references/useAbs.md) | Reactive `Math.abs` | EXTERNAL |
|
||||
| [`useAverage`](references/useAverage.md) | Get the average of an array reactively | EXTERNAL |
|
||||
| [`useCeil`](references/useCeil.md) | Reactive `Math.ceil` | EXTERNAL |
|
||||
| [`useClamp`](references/useClamp.md) | Reactively clamp a value between two other values | EXTERNAL |
|
||||
| [`useFloor`](references/useFloor.md) | Reactive `Math.floor` | EXTERNAL |
|
||||
| [`useMath`](references/useMath.md) | Reactive `Math` methods | EXTERNAL |
|
||||
| [`useMax`](references/useMax.md) | Reactive `Math.max` | EXTERNAL |
|
||||
| [`useMin`](references/useMin.md) | Reactive `Math.min` | EXTERNAL |
|
||||
| [`usePrecision`](references/usePrecision.md) | Reactively set the precision of a number | EXTERNAL |
|
||||
| [`useProjection`](references/useProjection.md) | Reactive numeric projection from one domain to another | EXTERNAL |
|
||||
| [`useRound`](references/useRound.md) | Reactive `Math.round` | EXTERNAL |
|
||||
| [`useSum`](references/useSum.md) | Get the sum of an array reactively | EXTERNAL |
|
||||
| [`useTrunc`](references/useTrunc.md) | Reactive `Math.trunc` | EXTERNAL |
|
||||
|
||||
### @Motion
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useElementStyle`](https://motion.vueuse.org/api/use-element-style) | Sync a reactive object to a target element CSS styling | EXTERNAL |
|
||||
| [`useElementTransform`](https://motion.vueuse.org/api/use-element-transform) | Sync a reactive object to a target element CSS transform. | EXTERNAL |
|
||||
| [`useMotion`](https://motion.vueuse.org/api/use-motion) | Putting your components in motion. | EXTERNAL |
|
||||
| [`useMotionProperties`](https://motion.vueuse.org/api/use-motion-properties) | Access Motion Properties for a target element. | EXTERNAL |
|
||||
| [`useMotionVariants`](https://motion.vueuse.org/api/use-motion-variants) | Handle the Variants state and selection. | EXTERNAL |
|
||||
| [`useSpring`](https://motion.vueuse.org/api/use-spring) | Spring animations. | EXTERNAL |
|
||||
|
||||
### @Router
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useRouteHash`](references/useRouteHash.md) | Shorthand for a reactive `route.hash` | EXTERNAL |
|
||||
| [`useRouteParams`](references/useRouteParams.md) | Shorthand for a reactive `route.params` | EXTERNAL |
|
||||
| [`useRouteQuery`](references/useRouteQuery.md) | Shorthand for a reactive `route.query` | EXTERNAL |
|
||||
|
||||
### @RxJS
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`from`](references/from.md) | Wrappers around RxJS's [`from()`](https://rxjs.dev/api/index/function/from) and [`fromEvent()`](https://rxjs.dev/api/index/function/fromEvent) to allow them to accept `ref`s | EXTERNAL |
|
||||
| [`toObserver`](references/toObserver.md) | Sugar function to convert a `ref` into an RxJS [Observer](https://rxjs.dev/guide/observer) | EXTERNAL |
|
||||
| [`useExtractedObservable`](references/useExtractedObservable.md) | Use an RxJS [`Observable`](https://rxjs.dev/guide/observable) as extracted from one or more composables | EXTERNAL |
|
||||
| [`useObservable`](references/useObservable.md) | Use an RxJS [`Observable`](https://rxjs.dev/guide/observable) | EXTERNAL |
|
||||
| [`useSubject`](references/useSubject.md) | Bind an RxJS [`Subject`](https://rxjs.dev/guide/subject) to a `ref` and propagate value changes both ways | EXTERNAL |
|
||||
| [`useSubscription`](references/useSubscription.md) | Use an RxJS [`Subscription`](https://rxjs.dev/guide/subscription) without worrying about unsubscribing from it or creating memory leaks | EXTERNAL |
|
||||
| [`watchExtractedObservable`](references/watchExtractedObservable.md) | Watch the values of an RxJS [`Observable`](https://rxjs.dev/guide/observable) as extracted from one or more composables | EXTERNAL |
|
||||
|
||||
### @SchemaOrg
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`createSchemaOrg`](https://vue-schema-org.netlify.app/api/core/create-schema-org.html) | Create the schema.org manager instance. | EXTERNAL |
|
||||
| [`useSchemaOrg`](https://vue-schema-org.netlify.app/api/core/use-schema-org.html) | Update schema.org reactively. | EXTERNAL |
|
||||
|
||||
### @Sound
|
||||
|
||||
| Function | Description | Invocation |
|
||||
|----------|-------------|------------|
|
||||
| [`useSound`](https://github.com/vueuse/sound#examples) | Play sound effects reactively. | EXTERNAL |
|
||||
|
||||
|
||||
5
.claude/skills/vueuse-functions/SYNC.md
Normal file
5
.claude/skills/vueuse-functions/SYNC.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Sync Info
|
||||
|
||||
- **Source:** `vendor/vueuse/skills/vueuse-functions`
|
||||
- **Git SHA:** `2b8714473501bbdd4a2c7635db40c1b2b6b2fff1`
|
||||
- **Synced:** 2026-01-30
|
||||
159
.claude/skills/vueuse-functions/references/computedAsync.md
Normal file
159
.claude/skills/vueuse-functions/references/computedAsync.md
Normal file
@@ -0,0 +1,159 @@
|
||||
---
|
||||
category: Reactivity
|
||||
alias: asyncComputed
|
||||
---
|
||||
|
||||
# computedAsync
|
||||
|
||||
Computed for async functions
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { computedAsync } from '@vueuse/core'
|
||||
import { shallowRef } from 'vue'
|
||||
|
||||
const name = shallowRef('jack')
|
||||
|
||||
const userInfo = computedAsync(
|
||||
async () => {
|
||||
return await mockLookUp(name.value)
|
||||
},
|
||||
null, /* initial state */
|
||||
)
|
||||
```
|
||||
|
||||
### Evaluation State
|
||||
|
||||
You will need to pass a ref to track if the async function is evaluating.
|
||||
|
||||
```ts
|
||||
import { computedAsync } from '@vueuse/core'
|
||||
import { shallowRef } from 'vue'
|
||||
|
||||
const evaluating = shallowRef(false)
|
||||
|
||||
const userInfo = computedAsync(
|
||||
async () => { /* your logic */ },
|
||||
null,
|
||||
evaluating,
|
||||
)
|
||||
```
|
||||
|
||||
### onCancel
|
||||
|
||||
When the computed source changed before the previous async function gets resolved, you may want to cancel the previous one. Here is an example showing how to incorporate with the fetch API.
|
||||
|
||||
```ts
|
||||
import { computedAsync } from '@vueuse/core'
|
||||
// ---cut---
|
||||
const packageName = shallowRef('@vueuse/core')
|
||||
|
||||
const downloads = computedAsync(async (onCancel) => {
|
||||
const abortController = new AbortController()
|
||||
|
||||
onCancel(() => abortController.abort())
|
||||
|
||||
return await fetch(
|
||||
`https://api.npmjs.org/downloads/point/last-week/${packageName.value}`,
|
||||
{ signal: abortController.signal },
|
||||
)
|
||||
.then(response => response.ok ? response.json() : { downloads: '—' })
|
||||
.then(result => result.downloads)
|
||||
}, 0)
|
||||
```
|
||||
|
||||
### Lazy
|
||||
|
||||
By default, `computedAsync` will start resolving immediately on creation, specify `lazy: true` to make it start resolving on the first accessing.
|
||||
|
||||
```ts
|
||||
import { computedAsync } from '@vueuse/core'
|
||||
import { shallowRef } from 'vue'
|
||||
|
||||
const evaluating = shallowRef(false)
|
||||
|
||||
const userInfo = computedAsync(
|
||||
async () => { /* your logic */ },
|
||||
null,
|
||||
{ lazy: true, evaluating },
|
||||
)
|
||||
```
|
||||
|
||||
## Caveats
|
||||
|
||||
- Just like Vue's built-in `computed` function, `computedAsync` does dependency tracking and is automatically re-evaluated when dependencies change. Note however that only dependency referenced in the first call stack are considered for this. In other words: **Dependencies that are accessed asynchronously will not trigger re-evaluation of the async computed value.**
|
||||
|
||||
- As opposed to Vue's built-in `computed` function, re-evaluation of the async computed value is triggered whenever dependencies are changing, regardless of whether its result is currently being tracked or not.
|
||||
|
||||
## Type Declarations
|
||||
|
||||
```ts
|
||||
/**
|
||||
* Handle overlapping async evaluations.
|
||||
*
|
||||
* @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished
|
||||
*/
|
||||
export type AsyncComputedOnCancel = (cancelCallback: Fn) => void
|
||||
export interface AsyncComputedOptions<Lazy = boolean> {
|
||||
/**
|
||||
* Should value be evaluated lazily
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
lazy?: Lazy
|
||||
/**
|
||||
* Ref passed to receive the updated of async evaluation
|
||||
*/
|
||||
evaluating?: Ref<boolean>
|
||||
/**
|
||||
* Use shallowRef
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
shallow?: boolean
|
||||
/**
|
||||
* The flush option allows for greater control over the timing of a history point, default to `pre`
|
||||
*
|
||||
* Possible values: `pre`, `post`, `sync`
|
||||
*
|
||||
* It works in the same way as the flush option in watch and watch effect in vue reactivity
|
||||
* @default 'sync'
|
||||
*/
|
||||
flush?: WatchOptionFlush
|
||||
/**
|
||||
* Callback when error is caught.
|
||||
*/
|
||||
onError?: (e: unknown) => void
|
||||
}
|
||||
/**
|
||||
* Create an asynchronous computed dependency.
|
||||
*
|
||||
* @see https://vueuse.org/computedAsync
|
||||
* @param evaluationCallback The promise-returning callback which generates the computed value
|
||||
* @param initialState The initial state, used until the first evaluation finishes
|
||||
* @param optionsOrRef Additional options or a ref passed to receive the updates of the async evaluation
|
||||
*/
|
||||
export declare function computedAsync<T>(
|
||||
evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,
|
||||
initialState: T,
|
||||
optionsOrRef: AsyncComputedOptions<true>,
|
||||
): ComputedRef<T>
|
||||
export declare function computedAsync<T>(
|
||||
evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,
|
||||
initialState: undefined,
|
||||
optionsOrRef: AsyncComputedOptions<true>,
|
||||
): ComputedRef<T | undefined>
|
||||
export declare function computedAsync<T>(
|
||||
evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,
|
||||
initialState: T,
|
||||
optionsOrRef?: Ref<boolean> | AsyncComputedOptions,
|
||||
): Ref<T>
|
||||
export declare function computedAsync<T>(
|
||||
evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,
|
||||
initialState?: undefined,
|
||||
optionsOrRef?: Ref<boolean> | AsyncComputedOptions,
|
||||
): Ref<T | undefined>
|
||||
/** @deprecated use `computedAsync` instead */
|
||||
export declare const asyncComputed: typeof computedAsync
|
||||
```
|
||||
62
.claude/skills/vueuse-functions/references/computedEager.md
Normal file
62
.claude/skills/vueuse-functions/references/computedEager.md
Normal file
@@ -0,0 +1,62 @@
|
||||
---
|
||||
category: Reactivity
|
||||
alias: eagerComputed
|
||||
---
|
||||
|
||||
# computedEager
|
||||
|
||||
Eager computed without lazy evaluation.
|
||||
|
||||
::: info
|
||||
This function will be removed in future version.
|
||||
:::
|
||||
|
||||
::: tip
|
||||
Note💡: If you are using Vue 3.4+, you can use `computed` right away, you no longer need this function.
|
||||
In Vue 3.4+, if the computed new value does not change, `computed`, `effect`, `watch`, `watchEffect`, `render` dependencies will not be triggered.
|
||||
See: https://github.com/vuejs/core/pull/5912
|
||||
:::
|
||||
|
||||
Learn more at [Vue: When a computed property can be the wrong tool](https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j).
|
||||
|
||||
- Use `computed()` when you have a complex calculation going on, which can actually profit from caching and lazy evaluation and should only be (re-)calculated if really necessary.
|
||||
- Use `computedEager()` when you have a simple operation, with a rarely changing return value – often a boolean.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { computedEager } from '@vueuse/core'
|
||||
|
||||
const todos = ref([])
|
||||
const hasOpenTodos = computedEager(() => !!todos.length)
|
||||
|
||||
console.log(hasOpenTodos.value) // false
|
||||
toTodos.value.push({ title: 'Learn Vue' })
|
||||
console.log(hasOpenTodos.value) // true
|
||||
```
|
||||
|
||||
## Type Declarations
|
||||
|
||||
```ts
|
||||
export type ComputedEagerOptions = WatchOptionsBase
|
||||
export type ComputedEagerReturn<T = any> = Readonly<ShallowRef<T>>
|
||||
/**
|
||||
*
|
||||
* @deprecated This function will be removed in future version.
|
||||
*
|
||||
* Note: If you are using Vue 3.4+, you can straight use computed instead.
|
||||
* Because in Vue 3.4+, if computed new value does not change,
|
||||
* computed, effect, watch, watchEffect, render dependencies will not be triggered.
|
||||
* refer: https://github.com/vuejs/core/pull/5912
|
||||
*
|
||||
* @param fn effect function
|
||||
* @param options WatchOptionsBase
|
||||
* @returns readonly shallowRef
|
||||
*/
|
||||
export declare function computedEager<T>(
|
||||
fn: () => T,
|
||||
options?: ComputedEagerOptions,
|
||||
): ComputedEagerReturn<T>
|
||||
/** @deprecated use `computedEager` instead */
|
||||
export declare const eagerComputed: typeof computedEager
|
||||
```
|
||||
86
.claude/skills/vueuse-functions/references/computedInject.md
Normal file
86
.claude/skills/vueuse-functions/references/computedInject.md
Normal file
@@ -0,0 +1,86 @@
|
||||
---
|
||||
category: Component
|
||||
---
|
||||
|
||||
# computedInject
|
||||
|
||||
Combine computed and inject
|
||||
|
||||
## Usage
|
||||
|
||||
In Provider Component
|
||||
|
||||
```ts twoslash include main
|
||||
import type { InjectionKey, Ref } from 'vue'
|
||||
import { provide } from 'vue'
|
||||
|
||||
interface Item {
|
||||
key: number
|
||||
value: string
|
||||
}
|
||||
|
||||
export const ArrayKey: InjectionKey<Ref<Item[]>> = Symbol('symbol-key')
|
||||
|
||||
const array = ref([{ key: 1, value: '1' }, { key: 2, value: '2' }, { key: 3, value: '3' }])
|
||||
|
||||
provide(ArrayKey, array)
|
||||
```
|
||||
|
||||
In Receiver Component
|
||||
|
||||
```ts
|
||||
// @filename: provider.ts
|
||||
// @include: main
|
||||
// ---cut---
|
||||
import { computedInject } from '@vueuse/core'
|
||||
|
||||
import { ArrayKey } from './provider'
|
||||
|
||||
const computedArray = computedInject(ArrayKey, (source) => {
|
||||
const arr = [...source.value]
|
||||
arr.unshift({ key: 0, value: 'all' })
|
||||
return arr
|
||||
})
|
||||
```
|
||||
|
||||
## Type Declarations
|
||||
|
||||
```ts
|
||||
export type ComputedInjectGetter<T, K> = (
|
||||
source: T | undefined,
|
||||
oldValue?: K,
|
||||
) => K
|
||||
export type ComputedInjectGetterWithDefault<T, K> = (
|
||||
source: T,
|
||||
oldValue?: K,
|
||||
) => K
|
||||
export type ComputedInjectSetter<T> = (v: T) => void
|
||||
export interface WritableComputedInjectOptions<T, K> {
|
||||
get: ComputedInjectGetter<T, K>
|
||||
set: ComputedInjectSetter<K>
|
||||
}
|
||||
export interface WritableComputedInjectOptionsWithDefault<T, K> {
|
||||
get: ComputedInjectGetterWithDefault<T, K>
|
||||
set: ComputedInjectSetter<K>
|
||||
}
|
||||
export declare function computedInject<T, K = any>(
|
||||
key: InjectionKey<T> | string,
|
||||
getter: ComputedInjectGetter<T, K>,
|
||||
): ComputedRef<K | undefined>
|
||||
export declare function computedInject<T, K = any>(
|
||||
key: InjectionKey<T> | string,
|
||||
options: WritableComputedInjectOptions<T, K>,
|
||||
): ComputedRef<K | undefined>
|
||||
export declare function computedInject<T, K = any>(
|
||||
key: InjectionKey<T> | string,
|
||||
getter: ComputedInjectGetterWithDefault<T, K>,
|
||||
defaultSource: T,
|
||||
treatDefaultAsFactory?: false,
|
||||
): ComputedRef<K>
|
||||
export declare function computedInject<T, K = any>(
|
||||
key: InjectionKey<T> | string,
|
||||
options: WritableComputedInjectOptionsWithDefault<T, K>,
|
||||
defaultSource: T | (() => T),
|
||||
treatDefaultAsFactory: true,
|
||||
): ComputedRef<K>
|
||||
```
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
category: Reactivity
|
||||
alias: controlledComputed
|
||||
---
|
||||
|
||||
# computedWithControl
|
||||
|
||||
Explicitly define the dependencies of computed.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts twoslash include main
|
||||
import { computedWithControl } from '@vueuse/core'
|
||||
|
||||
const source = ref('foo')
|
||||
const counter = ref(0)
|
||||
|
||||
const computedRef = computedWithControl(
|
||||
() => source.value, // watch source, same as `watch`
|
||||
() => counter.value, // computed getter, same as `computed`
|
||||
)
|
||||
```
|
||||
|
||||
With this, the changes of `counter` won't trigger `computedRef` to update but the `source` ref does.
|
||||
|
||||
```ts
|
||||
// @include: main
|
||||
// ---cut---
|
||||
console.log(computedRef.value) // 0
|
||||
|
||||
counter.value += 1
|
||||
|
||||
console.log(computedRef.value) // 0
|
||||
|
||||
source.value = 'bar'
|
||||
|
||||
console.log(computedRef.value) // 1
|
||||
```
|
||||
|
||||
### Manual Triggering
|
||||
|
||||
You can also manually trigger the update of the computed by:
|
||||
|
||||
```ts
|
||||
// @include: main
|
||||
// ---cut---
|
||||
const computedRef = computedWithControl(
|
||||
() => source.value,
|
||||
() => counter.value,
|
||||
)
|
||||
|
||||
computedRef.trigger()
|
||||
```
|
||||
|
||||
### Deep Watch
|
||||
|
||||
Unlike `computed`, `computedWithControl` is shallow by default.
|
||||
You can specify the same options as `watch` to control the behavior:
|
||||
|
||||
```ts
|
||||
const source = ref({ name: 'foo' })
|
||||
|
||||
const computedRef = computedWithControl(
|
||||
source,
|
||||
() => counter.value,
|
||||
{ deep: true },
|
||||
)
|
||||
```
|
||||
|
||||
## Type Declarations
|
||||
|
||||
```ts
|
||||
export interface ComputedWithControlRefExtra {
|
||||
/**
|
||||
* Force update the computed value.
|
||||
*/
|
||||
trigger: () => void
|
||||
}
|
||||
export interface ComputedRefWithControl<T>
|
||||
extends ComputedRef<T>,
|
||||
ComputedWithControlRefExtra {}
|
||||
export interface WritableComputedRefWithControl<T>
|
||||
extends WritableComputedRef<T>,
|
||||
ComputedWithControlRefExtra {}
|
||||
export type ComputedWithControlRef<T = any> =
|
||||
| ComputedRefWithControl<T>
|
||||
| WritableComputedRefWithControl<T>
|
||||
export declare function computedWithControl<T>(
|
||||
source: WatchSource | MultiWatchSources,
|
||||
fn: ComputedGetter<T>,
|
||||
options?: WatchOptions,
|
||||
): ComputedRefWithControl<T>
|
||||
export declare function computedWithControl<T>(
|
||||
source: WatchSource | MultiWatchSources,
|
||||
fn: WritableComputedOptions<T>,
|
||||
options?: WatchOptions,
|
||||
): WritableComputedRefWithControl<T>
|
||||
/** @deprecated use `computedWithControl` instead */
|
||||
export declare const controlledComputed: typeof computedWithControl
|
||||
```
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
category: Utilities
|
||||
---
|
||||
|
||||
# createEventHook
|
||||
|
||||
Utility for creating event hooks
|
||||
|
||||
## Usage
|
||||
|
||||
Creating a function that uses `createEventHook`
|
||||
|
||||
```ts
|
||||
import { createEventHook } from '@vueuse/core'
|
||||
|
||||
export function useMyFetch(url) {
|
||||
const fetchResult = createEventHook<Response>()
|
||||
const fetchError = createEventHook<any>()
|
||||
|
||||
fetch(url)
|
||||
.then(result => fetchResult.trigger(result))
|
||||
.catch(error => fetchError.trigger(error.message))
|
||||
|
||||
return {
|
||||
onResult: fetchResult.on,
|
||||
onError: fetchError.on,
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Using a function that uses `createEventHook`
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useMyFetch } from './my-fetch-function'
|
||||
|
||||
const { onResult, onError } = useMyFetch('my api url')
|
||||
|
||||
onResult((result) => {
|
||||
console.log(result)
|
||||
})
|
||||
|
||||
onError((error) => {
|
||||
console.error(error)
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Type Declarations
|
||||
|
||||
```ts
|
||||
/**
|
||||
* The source code for this function was inspired by vue-apollo's `useEventHook` util
|
||||
* https://github.com/vuejs/vue-apollo/blob/v4/packages/vue-apollo-composable/src/util/useEventHook.ts
|
||||
*/
|
||||
type Callback<T> =
|
||||
IsAny<T> extends true
|
||||
? (...param: any) => void
|
||||
: [T] extends [void]
|
||||
? (...param: unknown[]) => void
|
||||
: [T] extends [any[]]
|
||||
? (...param: T) => void
|
||||
: (...param: [T, ...unknown[]]) => void
|
||||
export type EventHookOn<T = any> = (fn: Callback<T>) => {
|
||||
off: () => void
|
||||
}
|
||||
export type EventHookOff<T = any> = (fn: Callback<T>) => void
|
||||
export type EventHookTrigger<T = any> = (
|
||||
...param: Parameters<Callback<T>>
|
||||
) => Promise<unknown[]>
|
||||
export interface EventHook<T = any> {
|
||||
on: EventHookOn<T>
|
||||
off: EventHookOff<T>
|
||||
trigger: EventHookTrigger<T>
|
||||
clear: () => void
|
||||
}
|
||||
export type EventHookReturn<T> = EventHook<T>
|
||||
/**
|
||||
* Utility for creating event hooks
|
||||
*
|
||||
* @see https://vueuse.org/createEventHook
|
||||
*
|
||||
* @__NO_SIDE_EFFECTS__
|
||||
*/
|
||||
export declare function createEventHook<T = any>(): EventHookReturn<T>
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
category: '@Math'
|
||||
---
|
||||
|
||||
# createGenericProjection
|
||||
|
||||
Generic version of `createProjection`. Accepts a custom projector function to map arbitrary type of domains.
|
||||
|
||||
Refer to `createProjection` and `useProjection`
|
||||
|
||||
## Type Declarations
|
||||
|
||||
```ts
|
||||
export type ProjectorFunction<F, T> = (
|
||||
input: F,
|
||||
from: readonly [F, F],
|
||||
to: readonly [T, T],
|
||||
) => T
|
||||
export type UseProjection<F, T> = (input: MaybeRefOrGetter<F>) => ComputedRef<T>
|
||||
export declare function createGenericProjection<F = number, T = number>(
|
||||
fromDomain: MaybeRefOrGetter<readonly [F, F]>,
|
||||
toDomain: MaybeRefOrGetter<readonly [T, T]>,
|
||||
projector: ProjectorFunction<F, T>,
|
||||
): UseProjection<F, T>
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user