Vue3提高效率小技巧

问题1:Vue3使用了setup API,无法访问到this,虽然提供了getCurrentInstance API,但访问全局变量时感觉比Vue2使用方式更繁琐了,因此想了个捷径(小菜鸟想法)

getCurrentInstance() 获取到全局对象挂载到window上,页面直接使用window.$this访问即可

// getThis.js
import { getCurrentInstance } from 'vue-demi'
const getThis = function () {
  window.$this = getCurrentInstance().appContext.config.globalProperties
}
export {
  getThis
}
// App.vue
import { getThis as getThisMountToWindow } from './utils/getThis.js'
onMounted(() => {
  getThisMountToWindow() // getCurrentInstance必须在生命周期中调用
})
// home.vue
const _this = window.$this

_this.$router.push()
_this.$api.xxx()
// ...

问题2:Vue3中无法通过$refs获取ref,虽然提供了getCurrentInstance API,但还是比较繁琐

配合$this使用以获得Vue2写法,效果更佳

// getThis.js
import { getCurrentInstance } from 'vue-demi'
const getCtxRefs = function () {
  return getCurrentInstance().ctx.$refs
}
export {
  getCtxRefs
}
// main.js
import { getCtxRefs } from './utils/getThis.js'
...
app.config.globalProperties.$getRefs = getCtxRefs
// home.vue
onMounted(() => {
  // 通过封装的getCtxRefs()获取到this.$refs
  _refs = _this.$getRefs()
  _refs.pc.style.color = 'blue'
  // ...
})

未完待续

posted on 2022-05-30 09:55  吴知木  阅读(211)  评论(0编辑  收藏  举报

导航