【问题标题】:How to use plugins like vue-resource when using Vue.js with Typescript?将 Vue.js 与 Typescript 一起使用时如何使用 vue-resource 等插件?
【发布时间】:2017-11-20 18:39:37
【问题描述】:

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

当我使用时

this.$http.post()

我得到错误:

错误 TS2339:“typeof Vue”类型上不存在属性“$http”。

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

<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 },
});

【问题讨论】:

  • 如果您使用import 语句而不是require 导入VueResource 会发生什么?我不使用打字稿,但$http 是未定义的,在js 中,使用require 时; import 工作正常。
  • 是的!做到了!太感谢了。由于一些较旧的错误,我不得不require它,但现在它似乎工作了。您可以将您的评论转换为答案。祝你有美好的一天。

标签: javascript typescript vue.js vue-resource


【解决方案1】:

VueResource 也使用import 而不是require

import VueResource from 'vue-resource'

【讨论】:

  • node_modules/vue-resource/t...' is not assignable to type 'PluginFunction&lt;any&gt;'.node_modules/vue-resource/t...' provides no match for the signature '(Vue: VueConstructor&lt;Vue&gt;, options?: any): void'.[39m
  • 我也遇到了这个问题:'Promise 类型的参数 | PluginFunction”的参数。类型“Promise”。类型“Promise, options?: any): void'
猜你喜欢
  • 2016-12-22
  • 2020-03-02
  • 2020-05-22
  • 2020-10-11
  • 2018-06-02
  • 2020-07-02
  • 2018-04-16
  • 2017-10-22
  • 1970-01-01
相关资源
最近更新 更多