vue3.0+TS 全局注入$store 类型及其他

1,430 阅读1分钟

ts 在注入插件到vue时会出现类型报错提示解决办法如下。

vue2.0 注入外部或自定义类型到vue


1 import Vue from "vue";
2 
3 declare module "vue/types/vue" {
4   interface Vue {
5     $store: any
6   }
7 }

vue3.0

vue到3.0以后,因为对ts包进行了升级改造,以前的注入方式无效,在调用时发现this.router调用并未提示于是参考了下router 调用并未提示于是参考了下router3.0导入方式

declare module '@vue/runtime-core' {
  export interface ComponentCustomOptions {
    /**
     * Guard called when the router is navigating to the route that is rendering
     * this component from a different route. Differently from `beforeRouteUpdate`
     * and `beforeRouteLeave`, `beforeRouteEnter` does not have access to the
     * component instance through `this` because it triggers before the component
     * is even mounted.
     *
     * @param to - RouteLocationRaw we are navigating to
     * @param from - RouteLocationRaw we are navigating from
     * @param next - function to validate, cancel or modify (by redirecting) the
     * navigation
     */
    beforeRouteEnter?: NavigationGuardWithThis<undefined>

    /**
     * Guard called whenever the route that renders this component has changed but
     * it is reused for the new route. This allows you to guard for changes in
     * params, the query or the hash.
     *
     * @param to - RouteLocationRaw we are navigating to
     * @param from - RouteLocationRaw we are navigating from
     * @param next - function to validate, cancel or modify (by redirecting) the
     * navigation
     */
    beforeRouteUpdate?: NavigationGuard

    /**
     * Guard called when the router is navigating away from the current route that
     * is rendering this component.
     *
     * @param to - RouteLocationRaw we are navigating to
     * @param from - RouteLocationRaw we are navigating from
     * @param next - function to validate, cancel or modify (by redirecting) the
     * navigation
     */
    beforeRouteLeave?: NavigationGuard
  }

  export interface ComponentCustomProperties {
    /**
     * Normalized current location. See {@link RouteLocationNormalizedLoaded}.
     */
    $route: RouteLocationNormalizedLoaded
    /**
     * {@link Router} instance used by the application.
     */
    $router: Router
  }
}

发现升级包变更为 declare module '@vue/runtime-core' ,于是改造如下,后续可以加入 httphttp、moment 等方便调用。

declare module '@vue/runtime-core'{
   const $store:any;
   export $store;
}