vue-demi

2023-08-16

前端

事物都是互相妥协的。就是冰山也会时而消融,时而重新凝聚。——爱默生

分享一个vue

https://github.com/vueuse/vue-demi

用来解决编写的代码在vue2vue3之间的兼容问题

安装:

1
npm i vue-demi

然后修改package.json,将vue 和@vue/composition-api添加到peerDependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"dependencies": {
"vue-demi": "latest"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^2.0.0 || >=3.0.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
},
"devDependencies": {
"vue": "^3.0.0" // or "^2.6.0" base on your preferred working environment
},
}

使用时,就从vue-demi

1
import { ref, reactive, defineComponent } from 'vue-demi'

例如这个例子:

https://github.com/vueuse/vue-demi/blob/main/examples/%40vue-demi/use-mouse/src/index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { ref, onMounted, onUnmounted } from 'vue-demi'

export function useMouse() {
const x = ref(0)
const y = ref(0)

const update = (e: MouseEvent) => {
x.value = e.pageX
y.value = e.pageY
}

onMounted(() => {
window.addEventListener('mousemove', update)
})

onUnmounted(() => {
window.removeEventListener('mousemove', update)
})

return {
x,
y
}
}