问题1:Vue3使用了setup API,无法访问到this,虽然提供了getCurrentInstance API,但访问全局变量时感觉比Vue2使用方式更繁琐了,因此想了个捷径(小菜鸟想法)
getCurrentInstance() 获取到全局对象挂载到window上,页面直接使用window.$this访问即可
| |
| import { getCurrentInstance } from 'vue-demi' |
| const getThis = function () { |
| window.$this = getCurrentInstance().appContext.config.globalProperties |
| } |
| export { |
| getThis |
| } |
| |
| import { getThis as getThisMountToWindow } from './utils/getThis.js' |
| onMounted(() => { |
| getThisMountToWindow() |
| }) |
| |
| const _this = window.$this |
| |
| _this.$router.push() |
| _this.$api.xxx() |
| |
问题2:Vue3中无法通过$refs获取ref,虽然提供了getCurrentInstance API,但还是比较繁琐
配合$this使用以获得Vue2写法,效果更佳
| |
| import { getCurrentInstance } from 'vue-demi' |
| const getCtxRefs = function () { |
| return getCurrentInstance().ctx.$refs |
| } |
| export { |
| getCtxRefs |
| } |
| |
| import { getCtxRefs } from './utils/getThis.js' |
| ... |
| app.config.globalProperties.$getRefs = getCtxRefs |
| |
| onMounted(() => { |
| |
| _refs = _this.$getRefs() |
| _refs.pc.style.color = 'blue' |
| |
| }) |
未完待续
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端