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

…衆ロ難τιáo~ 提交于 2019-12-01 18:13:00

问题


I started using Typescript and trying to apply it to my project. However, I can't get Vue.js plugins like vue-resource to work with it.

When I use

this.$http.post()

I get the error:

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

which makes sense because I am in a class context. But how can I do that? This is my full component:

<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>

And I register vue-resource in my main.ts like this:

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

回答1:


Use import instead of require for VueResource too.

import VueResource from 'vue-resource'


来源:https://stackoverflow.com/questions/44615445/how-to-use-plugins-like-vue-resource-when-using-vue-js-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!