分享一个vue
库
https://github.com/vueuse/vue-demi
用来解决编写的代码在vue2
和vue3
之间的兼容问题
安装:
代码语言:javascript复制npm i vue-demi
然后修改package.json
,将vue
和@vue/composition-api
添加到peerDependencies
中
{
"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
导
import { ref, reactive, defineComponent } from 'vue-demi'
例如这个例子:
https://github.com/vueuse/vue-demi/blob/main/examples/@vue-demi/use-mouse/src/index.ts
代码语言:javascript复制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
}
}