[Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript

Vue 2.2 introduced a simple dependency injection system, allowing you to use provide and inject in your component options. This lesson shows you how to use them using the @Inject and @Provide decorators in tandem!

 

When you want to provide some service or data from parent to child component you can use @Provide and @Inject.

 

Parent component:

<template>
  <div class="hello">
    <ChildComp :msg="'What a good day!'"/>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {Component, Provide} from 'vue-property-decorator'

import ChildComp from './Child.vue';

@Component({
})
export default class Hello extends Vue {

  @Provide('users')
  users = [
    {
      name: 'test',
      id: 0
    }
  ]

}
</script>

 

Child:

<template>
  <div>
      {{users}}
  </div>
</template>

<script lang="ts">

import Vue from 'vue'
import {Component, Inject} from 'vue-property-decorator'

@Component({})
export default class Child extends Vue {
    message: string = "Hello";

    @Inject('users') users;
}
</script>

 

posted @ 2017-09-14 20:01  Zhentiw  阅读(3088)  评论(0编辑  收藏  举报