首页 > 编程语言 >pinia源码解读二(定义模块)

pinia源码解读二(定义模块)

时间:2022-11-28 16:37:16浏览次数:49  
标签:__ && pinia setup 源码 模块 ._ id

定义模块 store.ts文件的defineStore方法

  • 判断是option写法还是setup写法 isSetupStore = typeof setup === 'function'

  • 内部创建useStore函数,并给函数绑定$id属性为用户设置的id,然后返回

  • 用户在外部任意位置调用useStore函数

    • 通过函数传参或者inject获取pinia实例,然后激活setActivePinia(pinia)

    • pinia._s.has(id) 判断store是否已经存在,没有就创建,有就直接返回

    • 创建时,如果是option类型先执行createOptionsStore,在该函数内部执行createSetupStore,如果是setup则直接进行createSetupStore

export function defineStore(
  // TODO: add proper types from above
  idOrOptions: any,
  setup?: any,
  setupOptions?: any
): StoreDefinition {
  let id: string
  let options:
    | DefineStoreOptions<
        string,
        StateTree,
        _GettersTree<StateTree>,
        _ActionsTree
      >
    | DefineSetupStoreOptions<
        string,
        StateTree,
        _GettersTree<StateTree>,
        _ActionsTree
      >

  const isSetupStore = typeof setup === 'function'
  if (typeof idOrOptions === 'string') {
    id = idOrOptions
    // the option store setup will contain the actual options in this case
    options = isSetupStore ? setupOptions : setup
  } else {
    options = idOrOptions
    id = idOrOptions.id
  }

  function useStore(pinia?: Pinia | null, hot?: StoreGeneric): StoreGeneric {
    const currentInstance = getCurrentInstance()
    pinia =
      // in test mode, ignore the argument provided as we can always retrieve a
      // pinia instance with getActivePinia()
      (__TEST__ && activePinia && activePinia._testing ? null : pinia) ||
      (currentInstance && inject(piniaSymbol))
    if (pinia) setActivePinia(pinia)

    if (__DEV__ && !activePinia) {
      throw new Error(
        `[

标签:__,&&,pinia,setup,源码,模块,._,id
From: https://www.cnblogs.com/wzcsqaws/p/16932521.html

相关文章