为什么 vue-router 使用不推荐的 getCurrentInstance?

阅读 3.6k
1 个回答

按照鱿鱼须的原话就是:

Because the instance is an internal instance that exposes non-public APIs. Anything you use from that instance can technically break between any release types, since they are not subject to semver constraints.

同时也给出了应该如何解决问题:

I'm not sure why you need the setup context in nested composables, but explicitly passing arguments to composables make then less coupled to the consuming component, thus easier to understand and test in isolation.

In general a library designed to work with Composition API should expose special variables via its own composables (e.g. useRoute from vue-router) instead of the requiring the user to grab it from the instance.

主要还是 getCurrentInstance 是一个内部的API,并不是公开的API,使用内部API去实现一些业务功能,可能会因为后续 Vue 的版本迭代而造成业务上的 BUG。并且 Vue3Composition API 强调的就是业务的解耦和复用性,依赖组件实例属性并不是一个很好的开发方式。
vue 相关生态的使用其实就是他们内部的事情了,他们有完善的测试用例可以跑测试,但是我们并没有,如果后续的某一个版本Vue变更了这个API,那么如果没有经过完整测试就部署上去的项目就会出现大规模的BUG反馈了。

阅读更多

Unable to report missing search result · Issue #1775 · vuejs/docs
Why getCurrentInstance is descriped as anti pattern in application code? · Issue #1422 · vuejs/docs
getCurrentInstance type not correct · Issue #12596 · vuejs/vue
Vue 3: Is getCurrentInstance() deprecated? - Stack Overflow

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题