如何使用 TypeScript 在 Vue.js 中使用提供/注入 [英] How to use Provide/Inject in Vue.js with TypeScript

查看:47
本文介绍了如何使用 TypeScript 在 Vue.js 中使用提供/注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Vue.js 和 TypeScript 和 vue-property-decorator包裹.根据文档,理论上我可以做这样的事情:

I'm using Vue.js with TypeScript and the vue-property-decorator package. In theory I can do something like this, according to the documentation:

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

const s = Symbol('baz')

@Component
export class MyComponent extends Vue {
  @Provide() foo = 'foo'
  @Provide('bar') baz = 'bar'

  @Inject() foo: string
  @Inject('bar') bar: string
  @Inject(s) baz: string
}

但是,如果我想在不是组件的类上使用 @Provide@Inject 怎么办?例如,如果我有依赖于 ServiceAComponentA 依赖于 ServiceB.我该如何设置?

However, what if I want to use @Provide and @Inject on a class that is not a component? For example, if I have ComponentA that depends on ServiceA that depends on ServiceB. How can i set this up?

推荐答案

您可以使用 @Provide 装饰器从更高的组件中提供您想要的任何内容,然后使用@Inject.例如:

You provide anything you want from a higher component by using the @Provide decorator and then ask for it in a lower component by using @Inject. For example:

在父组件中,您使用 @Provide()

//Parent.vue
<template>
  <div>The parents value: {{this.providedValue}}</div>
  <child />
</template>

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

  @Component({components: Child})
  export default class Parent extends Vue {
    @Provide('key') private providedValue: string = 'The value';
  }
</script>

现在我们已经声明了一个名为 key 的值,它可以被所有子级使用,深度为多级:

Now we've declared a value with the name key that can be consumed by all children, multiple levels deep:

//Child.vue
<template>
  <div>The childs value: {{this.injectedValue}}</div>
</template>

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

  @Component
  export default class Child extends Vue {
    @Inject('key') private injectedValue!: string;
  }
</script>

属性 injectedValue 现在将由 Vue 注入,方法是在层次结构中向上移动,直到找到带有键 key 的提供值.

The property injectedValue will now be injected by Vue by walking up on the hierarchy until it finds a provided value with the key key.

如果你想要类似依赖注入的东西,最好在顶部提供值,在那里你创建你的 Vue 实例:

If you want something dependency injection-like, it's best to provide the value at the top, where you create your Vue instance:

//index.ts
import Vue from 'vue';
//... imports and configs
new Vue({
  el: '#app',
  // Provide values by returning a key-value pair
  provide: () => ({
    'key1': 'value1',
    'key2': 'value2'
  }),
  render: h => h(App)
});

现在你可以在这个 vue 实例的任何组件中使用 @Inject('key1').

Now you can use @Inject('key1') in any component of this vue instance.

这篇关于如何使用 TypeScript 在 Vue.js 中使用提供/注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆