在 Typescript 中使用 Vue.js 时如何使用 vue-resource 之类的插件?

How to use plugins like vue-resource when using Vue.js with Typescript?

我开始使用 Typescript 并尝试将其应用到我的项目中。但是,我无法使用像 vue-resource 这样的 Vue.js 插件。

当我使用

this.$http.post()

我收到错误:

error TS2339: Property '$http' does not exist on type 'typeof Vue'.

这是有道理的,因为我处于 class 环境中。但是我该怎么做呢?这是我的完整组件:

<template>
<div>
  <h1>Sign up</h1>

  <form>
    <div class="form-group">
      <label for="name">Name</label>
      <input v-model="name" type="text" class="form-control" name="name" placeholder="Name">
      <small class="form-text text-muted">Please provide a name.</small>
    </div>
    <div class="form-group">
      <label for="name">Password</label>
      <input v-model="password" type="password" class="form-control" name="password" placeholder="Password">
      <small class="form-text text-muted">Please provide a password.</small>
    </div>
    <input type="submit" class="btn btn-primary" value="Submit" @click.prevent="save">
  </form>
</div>
</template>

<script lang="ts">
import Component from 'vue-class-component'

@Component
export default class SignUp extends Vue {
  name: string = ''
  password: string = ''

  save(): void {
    this.$http.post('/api/sign-up', {
        name: this.name,
        password: this.password
      })
      .then((response: any) => {
        console.log(response)
      })
  }
}
</script>

然后我在我的 main.ts 中注册 vue-resource,如下所示:

import Vue from "vue"
import router from "./router"
import App from "./app"

const VueResource = require('vue-resource')

Vue.use(VueResource)

new Vue({
  el: "#app",
  router,
  template: "<App/>",
  components: { App },
});

VueResource 也使用 import 而不是 require

import VueResource from 'vue-resource'