使用Vue.js + TypeScript在Onsen中调用`this。$ ons.notification.alert(...)`进行编译后出错

问题描述 投票:0回答:1

我试图在Vue.js(2.5.17)+ TypeScript(3.0.0)应用程序中调用onsen UI(2.11.5)的$ons方法。

在模板中调用它时它工作正常,但是在Compiled successfully在Vue派生类中调用this.$ons.{method name}之后,它会在命令行中导致错误。

错误是:

ERROR in /Users/max/.../src/views/TestOns.vue
Property '$ons' does not exist on type 'TestOns'. Did you mean '$on'?

但是虽然存在编译器错误,但代码仍然有效,因此会弹出警报(1)和(2)。

<template>
  <v-ons-page>
    <app-header title="About" />
    <div class="content about">

      <!-- Next tag works fine, no errors -->
      <v-ons-button @click="$ons.notification.alert('You clicked me (1)')">
        Click me! (1)
      </v-ons-button>

      <!-- Next tag will call the method that causes an error -->
      <v-ons-button @click="clickMe2()">
        Click me! (2)
      </v-ons-button>

    </div>
  </v-ons-page>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class TestOns extends Vue {

  private clickMe2() {
    // Next line causes a compiler ERROR, but it works nevertheless!
    this.$ons.notification.alert('You clicked me! (2)')
  }

}
</script>

这就是我在main.ts所拥有的:

(...)
import Vue from 'vue';
import VueOnsen from 'vue-onsenui';
(...)
import 'onsenui/css/onsenui.css';
import 'onsenui/css/onsen-css-components.css';
(...)
Vue.use(VueOnsen);
(...)

我想出了一个解决方法,将属性绑定到模板上的函数调用:

<template>
  <v-ons-page :set-ons="setOns($ons)">
  ...
</template>

@Component
export default class TestOns extends Vue {
  ...

  private ons: any = undefined;

  public setOns(ons: any): string {
      console.log(ons);
      this.ons = ons;
      return '';
  }
...
}

然后你可以通过this.ons访问

this.ons.notification.alert('You clicked me! (2)')

您还可以将$ons作为参数传递给事件,例如@click="clickMe($ons)"

但我想知道,为什么在类中调用this.$ons的编译错误,如Onsen UI文档中所述。如果它确实有效,为什么会出错。

typescript vuejs2 onsen-ui
1个回答
0
投票

我找到了2个令人满意的解

第一个是在组件中声明成员变量。无需初始化。

@Component
export default class TestOns extends Vue {
  ...
  private $ons: any;
  ...
}

第二个是将此代码包含在src/main.ts中的任何位置:

declare module 'vue/types/vue' {
  interface Vue {
    $ons: any;
  }
}

文档here中描述的解决方案对我不起作用,包括使用以下内容创建文件src/types/ons.d.ts

import Vue from 'vue';
declare module 'vue/types/vue' {
  interface Vue {
    $ons: any;
  }
}

问题是这个文件似乎被忽略了,尽管它位于tsconfig.json中设置的类型定义的路径中。

© www.soinside.com 2019 - 2024. All rights reserved.