【问题标题】:Vue-toastification - Augmenting Types in vuejs 3 with typescript is not workingVue-toastification - 在 vuejs 3 中使用 typescript 增强类型不起作用
【发布时间】:2020-12-08 09:22:50
【问题描述】:

我正在尝试在我的 vue 3 项目中使用 vue-toast-notification。我面临的问题是 vue 增强类型。我已经看到其他答案并应用了,但它对我不起作用是错误

TS2339: Property '$toast' does not exist on type 'Vue<unknown, {}, {}>'.

我尝试调用 toast 方法的测试组件

import { Vue } from "vue-class-component";
export default class Login extends Vue {

  private StoreID = "";
  private StorePassword = "";
  private errorMessage = "";
  testToast(e)
  {
    e.preventDefault();
    const vm = new Vue()
   console.log(vm.$toast)
  }
}

我的 Tsconfig.json 文件

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "typeRoots": [
      "node_modules/@types",
      "typings/vue.d.ts"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

我的 vue.d.ts 在类型文件夹中。在 main.ts 文件所在项目的根目录下创建了 typings 文件夹。

// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'
import VueToast from 'vue-toast-notification';

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
  // 3. Declare augmentation for Vue
  interface Vue {
    $toast: VueToast
  }
}

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

    使用安装latest version

    npm install --save vue-toastification@next
    

    然后尝试将以下代码添加到main.ts中

    import { createApp } from 'vue'
    import App from './App.vue'
    import Toast from 'vue-toast-notification';
    
    declare module '@vue/runtime-core' {
      interface ComponentCustomProperties  {
          $toast: Toast
          
         }
       }
    let app=createApp(App)
    
    app.use(Toast,{})
    
    app.mount('#app')
    

    【讨论】:

    • 我试过上面的,错误消失了,渲染成功,但是在浏览器控制台上给我一个错误
    • index.min.js?b079:1 Uncaught TypeError: Cannot set property '$toast' of undefined at Object.a.install (index.min.js?b079:1) at Object.use (runtime-core.esm-bundler.js?5c40:2948) 在 eval (main.ts?bc82:34) 在 Module../src/main.ts (app.js:1381) 在 webpack_require (app.js:849) 在 fn (app.js:151) 在 Object.1 (app.js:1598) 在 webpack_require
    • 我说过这个组件不支持vue3
    猜你喜欢
    • 2021-03-26
    • 2022-12-10
    • 2020-04-10
    • 2021-11-11
    • 2019-02-18
    • 2020-05-27
    • 2022-10-17
    • 2021-09-10
    • 2021-04-05
    相关资源
    最近更新 更多