Vue.js에서 TypeScript를 사용하여 제공/인젝트를 사용하는 방법
Vue.js와 TypeScript 및 vue-property-decorator 패키지를 함께 사용하고 있습니다.설명서에 따르면 이론적으로 다음과 같은 작업을 수행할 수 있습니다.
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
컴포넌트가 아닌 클래스에서요?예를 들어, 만약ComponentA
에 따라 다르다ServiceA
에 따라 다르다ServiceB
어떻게 하면 셋업 할 수 있을까요?
상위 컴포넌트에서 원하는 모든 것을 제공하려면@Provide
데코레이터를 사용하여 아래 컴포넌트에 의뢰합니다.@Inject
. 예:
상위 컴포넌트에서는 값을 다음과 같이 입력합니다.@Provide(<someKey>)
//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
모든 어린이가 섭취할 수 있으며, 여러 레벨의 깊이가 있습니다.
//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는 키를 사용하여 제공된 값을 찾을 때까지 계층 위로 이동함으로써 Vue에 의해 주입됩니다.key
.
종속성 주입과 같은 항목을 원하는 경우 Vue 인스턴스를 생성하는 맨 위에 값을 제공하는 것이 가장 좋습니다.
//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)
});
이제 사용할 수 있습니다.@Inject('key1')
이 Vue 인스턴스의 모든 컴포넌트에서 사용할 수 있습니다.
vue 3 및 클래스 스타일의 컴포넌트를 사용할 수 있습니다.이 경우 다음과 같이 프로바이더/인젝트를 정의해야 합니다.
vue 3에서는 컴포넌트 주석을 제외하고 옵션 주석이 있으며 이를 사용하여 제공/주입 파라미터를 정의합니다.상세 정보
// Parent component
import { Vue, Options } from "vue-class-component";
import { computed } from "@vue/reactivity";
@Options({
provide: {
staticParameter: 'static value',
reactiveParameter: computed(() => 'Normal computed value'),
},
})
export default class ParentComponent extends Vue {}
// Child component
import { Vue, Options } from "vue-class-component";
@Options({
inject: ["staticParameter", "reactiveParameter"],
})
export default class Timer extends Vue {
staticParameter!: string;
reactiveParameter!:string
}
언급URL : https://stackoverflow.com/questions/46928713/how-to-use-provide-inject-in-vue-js-with-typescript
'programing' 카테고리의 다른 글
Maven이 실행할 JUnit 테스트를 찾을 수 없습니다. (0) | 2022.08.12 |
---|---|
vuej의 커스텀 테이블 컴포넌트에서 슬롯/스코프 슬롯을 사용하는 방법 (0) | 2022.08.12 |
nCr을 계산하는 더 좋은 방법은 무엇입니까? (0) | 2022.08.12 |
vue-js-modal 대화 상자 열기 전 및 닫기 전에 전달하려면 어떻게 해야 합니까? (0) | 2022.08.12 |
실제 가동 중인 vue-router(Go와 함께 사용) (0) | 2022.08.12 |