@vert/core
Version:
Library to build OOP applications which are based on Vue.
131 lines (103 loc) • 2.28 kB
Markdown
# Inject service into vue component.
Let's say we have these services:
```typescript
// Your services.
import { Injectable } from '@vert/core'
()
class Http {
async get () {
// ...
}
async post () {
// ...
}
}
()
class BookshelfService {
async getBookshelfData () {
}
constructor (
private http: Http
) {}
}
()
class UserService {
async getUserData (id: number) {
let data: Account = null
let error: Error = null
try {
data = await this.http.get(...)
} catch (exception) {
error = exception
}
return {
data, error
}
}
constructor (
private http: Http
) {}
}
()
class Hinter {
info (message: string) {}
warn (message: string) {}
success (message: string) {}
error (message: string) {}
}
export {
BookshelfService,
Hinter,
UserService
}
```
And here is our vue component:
```vue
<template lang="pug">
// ...
</template>
<style lang="stylus" scoped>
/* ... */
</style>
<script lang="ts" src="./index.ts"></script>
```
We are going to inject these services to this component:
```typescript
import Vue from 'vue'
import { Component } from '@vert/core'
import { BookshelfService, Hinter, UserService } from './services'
export default class MyComponent extends Vue {
private userData: Account = null
private bookshelfData: BookShelf = null
private userId: number = 0
private async getUserData () {
const { data, error } = await this.userSrv.getUserData(this.userId)
if (error) {
this.hinter.error(error.message)
return
}
this.userData = data
}
private async getBookshelfInfo () {
const { data, error } = await this.bookshelfSrv.getBookshelfData()
if (error) {
this.hinter.error(error.message)
return
}
this.bookshelfData = data
}
created () {
this.getUserData()
this.getBookshelfInfo()
}
// Service Injection.
constructor (
private bookshelfSrv: BookshelfService,
private userSrv: UserService,
private hinter: Hinter
) {
super()
}
}
```