VueUse使用
基于Vue组合式API的实用工具集
# 为何用它
中文官网:https://www.vueusejs.com/ (opens new window)
- 功能丰富,有针对数据缓存、浏览器、元素、组件、时间处理、数据监听等模块都有功能
- 实用性高:适用于vue3.x和2.x版本
- 使用灵活
# 使用案例
- 具有自动数据持久性的响应式暗黑模式。
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)
1
2
3
4
2
3
4
- 具有自动数据持久化的响应式颜色模式
<UseColorMode v-slot="{ mode }">
<button @click="mode = mode === 'dark' ? 'light' : 'dark'">
Mode {{ mode }}
</button>
</UseColorMode>
1
2
3
4
5
2
3
4
5
import { useColorMode } from '@vueuse/core'
const mode = useColorMode({
attribute: 'theme',
modes: {
// custom colors
dim: 'dim',
cafe: 'cafe',
},
}) // Ref<'dark' | 'light' | 'dim' | 'cafe'>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
- 记录最后一次更改的时间戳
import { useLastChanged } from '@vueuse/core'
const a = ref(0)
const lastChanged = useLastChanged(a)
a.value = 1
console.log(lastChanged.value)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
- 跟踪元素在视口中的可见性
<template>
<div ref="target">
<h1>Hello world</h1>
</div>
</template>
<script>
import { ref } from 'vue'
import { useElementVisibility } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = useElementVisibility(target)
return {
target,
targetIsVisible,
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- 响应式监听目标元素的可见性。
<div ref="target">
<h1>Hello world</h1>
</div>
1
2
3
2
3
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
)
return {
target,
targetIsVisible,
}
},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- 操作css变量
import { useCssVar } from '@vueuse/core'
const el = ref(null)
const color = useCssVar('--color', el)
const elv = ref(null)
const key = ref('--color')
const colorVal = useCssVar(key, elv)
const someEl = ref(null)
const color = useCssVar('--color', someEl, { initialValue: '#eee' })
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 剪贴板命令
import { useClipboard } from '@vueuse/core'
const source = ref('Hello')
const { text, copy, copied, isSupported } = useClipboard({ source })
1
2
3
4
5
2
3
4
5
<div v-if="isSupported">
<button @click='copy(source)'>
<!-- by default, `copied` will be reset in 1.5s -->
<span v-if='!copied'>Copy</span>
<span v-else>Copied!</span>
</button>
<p>
Current copied: <code>{{ text || 'none' }}</code>
</p>
</div>
<p v-else>
Your browser does not support Clipboard API
</p>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
上次更新: 2024/01/19, 09:00:06