vue-demi

2023-08-17 11:06:46 浏览数 (1)

分享一个vue

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

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

安装:

代码语言:javascript复制
npm i vue-demi

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

代码语言:javascript复制
{
  "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

代码语言:javascript复制
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
  }
}

0 人点赞