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   吴知木  阅读(226)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示