Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

同一个组件中能否注入两个不同的实例? #2

Open
Lin-Ya opened this issue Nov 30, 2024 · 0 comments
Open

同一个组件中能否注入两个不同的实例? #2

Lin-Ya opened this issue Nov 30, 2024 · 0 comments

Comments

@Lin-Ya
Copy link

Lin-Ya commented Nov 30, 2024

例子:有父子两个组件: Father.vue 和 Child.vue

// Father.vue
<script setup lang="tsx">
import { onProvider, useDependency } from 'packages'
import Child from './components/Child.vue'
import { TestService } from './test.service'
import { Quantity } from '@wendellhu/redi'

onProvider([[TestService]])
const testService = useDependency(TestService, {
    self: true
})

function changeTest(a: any) {
    testService.inc()
}
</script>

<template>
    Father.vue: {{ testService.count }}
    <button @click="changeTest">修改</button>
    <div>
        <Child />
    </div>
</template>
// Child.vue
<script setup lang="ts">
import { TestService } from '@/test.service'
import { onProvider, useDependency } from 'packages'
import { ref } from 'vue'

onProvider([[TestService]])

const testService = useDependency(TestService, { self: true }) // 注入一个新的实例
const FatherTestService = useDependency(TestService, {self: false}) // 注入父组件的实例
</script>

<template>
    <div>
        <h1>父依赖, {{ FatherTestService.count }}</h1>
        <button @click="FatherTestService.inc()">add</button>
    </div>
    <div>
        <h1>子依赖, {{ testService.count }}</h1>
        <button @click="testService.inc()">add</button>
    </div>
</template>
// main.ts
import { Inject } from '@wendellhu/redi'
import { CREATED_VUE_APP_EXECUTION } from 'packages/hooks/token'
import { vdi } from 'packages/use'
import { createApp } from 'vue'
import { AppRoutes } from './app.routes'
import AppVue from './App.vue'
import { TestService } from './test.service'

class TestStartupService {
    constructor(@Inject(TestService) public t: TestService) {
        console.log(11, this.t)
    }
}

createApp(AppVue)
    .use(
        vdi([
            [TestService],
            [CREATED_VUE_APP_EXECUTION, { useClass: TestStartupService }]
        ])
    )
    .use(AppRoutes)
    .mount('#app')

但是上述代码的结果,每个 testService.count 的值都是一样的。我翻查了一下 vdi/packages/hooks/useDependency.ts,发现里面 options.self 好像并没有直接使用😂

我想了解,如果需要在一个组件里注入父组件已经注入的依赖,自身也想注入一个完全独立的依赖,应该怎么做?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant