美文网首页
[Vue warn]: injection "Symbol()"

[Vue warn]: injection "Symbol()"

作者: _十六 | 来源:发表于2021-12-10 15:33 被阅读0次

我的原因是因为:在上级组件和下级组件都使用 useStore() 获取 store

// store.ts
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

import { app, AppState } from './modules/app'

// 为 store state 声明类型
export interface State {
  app: AppState
}

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  modules: {
    app
  }
})

export function useStore() {
  return baseUseStore(key)
}

解决方案是:使用 Provide / Inject
在上级组件中获取一次 store,然后使用provide发布出去,下级组件通过inject引入使用即可

// App.vue
<script setup lang="ts">
import { provide } from 'vue'
import { useStore } from '@/store'

const store = useStore()
provide('store', store)
</script>

<template>
  <router-view />
</template>

使用

// home.vue
<script setup lang="ts">
import { inject } from 'vue'

const store: any = inject('store')
const sidebar = computed(() => store.state.app.sidebar)
</script>

相关文章

网友评论

      本文标题:[Vue warn]: injection "Symbol()"

      本文链接:https://www.haomeiwen.com/subject/znbcfrtx.html