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

I started using Typescript and tried to apply it to my project. However, I cannot get Vue.js plugins, such as vue-resource, to work with it.

When i use

this.$http.post()

I get an error message:

error TS2339: The '$ http' property does not exist in typeof Vue type.

which makes sense because I'm in the context of a class. But how can I do this? This is my complete 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 the vue resource main.tsas follows:

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 },
});
+4
source share
1 answer

Use importinstead requirefor VueResource too.

import VueResource from 'vue-resource'
+2

Source: https://habr.com/ru/post/1679559/


All Articles