vuex#Store TypeScript Examples

The following examples show how to use vuex#Store. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: namespaced.ts    From vuex-composition-helpers with MIT License 6 votes vote down vote up
export function createNamespacedHelpers<TState = any, TGetters = any, TActions = any, TMutations = any>(storeOrNamespace: Store<any> | string, namespace?: string):{
	useState: (map?: KnownKeys<TState>[]) => RefTypes<TState>;
	useGetters: (map?: KnownKeys<TGetters>[]) => ExtractGetterTypes<TGetters>;
	useMutations: (map?: KnownKeys<TMutations>[]) => ExtractTypes<TMutations, Function>;
	useActions: (map?: KnownKeys<TActions>[]) => ExtractTypes<TActions, Function>;
} {
	let store: Store<any> | Nullish = undefined;
	if (arguments.length === 1) {
		namespace = storeOrNamespace as string;
	} else {
		store = storeOrNamespace as Store<any>;
		if (!namespace) {
			throw new Error('Namespace is missing to provide namespaced helpers')
		}
	}
	return {
		useState: (map?: KnownKeys<TState>[]) => useState(store, namespace as string, map),
		useGetters: (map?: KnownKeys<TGetters>[]) => useGetters(store, namespace as string, map),
		useMutations: (map?: KnownKeys<TMutations>[]) => useMutations(store, namespace as string, map),
		useActions: (map?: KnownKeys<TActions>[]) => useActions(store, namespace as string, map),
	}
}
Example #2
Source File: Helpers.ts    From vuex-orm-next with MIT License 6 votes vote down vote up
export function fillState(store: Store<any>, entities: Entities): void {
  for (const entity in entities) {
    if (!store.state.entities[entity]) {
      store.state.entities[entity] = { data: {} }
    }

    store.state.entities[entity].data = entities[entity]
  }
}
Example #3
Source File: index.ts    From vue3-ts-base with MIT License 6 votes vote down vote up
store: Store<StateType> = createStore({
  strict: true,
  mutations,
  actions: {},
  modules: { ...modules },
  plugins:
    process.env.NODE_ENV !== 'production'
      ? [
          createLogger(),
          createPersistedState({
            paths: ['app', 'console', 'user']
          })
        ]
      : [
          createPersistedState({
            paths: ['app', 'console', 'user']
          })
        ]
})
Example #4
Source File: Store.ts    From vuex-orm-next with MIT License 6 votes vote down vote up
/**
 * Mixin repo function to the store.
 */
function mixinRepoFunction(store: Store<any>): void {
  store.$repo = function (modelOrRepository: any, connection?: string): any {
    let database: Database

    if (connection) {
      if (!(connection in store.$databases)) {
        database = createDatabase(store, { namespace: connection })
        database.start()
      } else {
        database = store.$databases[connection]
      }
    } else {
      database = store.$database
    }

    const repository = modelOrRepository._isRepository
      ? new modelOrRepository(database).initialize()
      : new Repository(database).initialize(modelOrRepository)

    try {
      database.register(repository.getModel())
    } catch (e) {
    } finally {
      return repository
    }
  }
}
Example #5
Source File: index.ts    From vue3-cesium-typescript-start-up-template with MIT License 6 votes vote down vote up
loadDefault3DTiles = (viewer: Viewer, store: Store<RootState>): void => {
  const jtPrimitives =
    store.state.jtCesiumVue.cesiumData.jtPrimitive.jtPrimitives
  const len = jtPrimitives.length
  for (let i = 0; i < len; ++i) {
    const jtPri = jtPrimitives[i]
    if (jtPri.name !== '成都建筑群') {
      continue
    }

    const pri = viewer?.jt?.primitiveManager.getPrimitiveByJTPrimitiveIndex(i)
    if (!pri.show) {
      pri.show = true
      store.dispatch(
        `jtCesiumVue/cesiumData/jtPrimitive/${JTPrimitiveActionTypes.SYNC_JTPRIMITIVES}`,
        viewer
      )
    }
    break
  }
}
Example #6
Source File: Store.ts    From vuex-orm-next with MIT License 6 votes vote down vote up
/**
 * Execute registered plugins.
 */
function installPlugins(store: Store<any>): void {
  plugins.forEach((plugin) => {
    const { func, options } = plugin

    func.install(store, components, options)
  })
}
Example #7
Source File: useLayoutControl.ts    From vue3-cesium-typescript-start-up-template with MIT License 6 votes vote down vote up
export default function () {
  function hideAllLayout(store: Store<RootState>) {
    store.dispatch(
      `jtCesiumVue/layout/${LayoutActionTypes.SET_SHOW_TOOLBAR}`,
      false
    )
    store.dispatch(
      `jtCesiumVue/layout/${LayoutActionTypes.SET_SHOW_BROWSER_PANEL}`,
      false
    )
    store.dispatch(
      `jtCesiumVue/layout/${LayoutActionTypes.SET_SHOW_SETTING_BUTTON}`,
      false
    )
  }

  function defaultLayout(store: Store<RootState>) {
    store.dispatch(
      `jtCesiumVue/layout/${LayoutActionTypes.SET_SHOW_TOOLBAR}`,
      true
    )
    store.dispatch(
      `jtCesiumVue/layout/${LayoutActionTypes.SET_SHOW_BROWSER_PANEL}`,
      true
    )
    store.dispatch(
      `jtCesiumVue/layout/${LayoutActionTypes.SET_SHOW_SETTING_BUTTON}`,
      false
    )
  }

  return {
    hideAllLayout,
    defaultLayout,
  }
}
Example #8
Source File: Store.ts    From vuex-orm-next with MIT License 6 votes vote down vote up
/**
 * Create a new database and connect to the store.
 */
function createDatabase(
  store: Store<any>,
  options: FilledInstallOptions
): Database {
  const database = new Database()
    .setStore(store)
    .setConnection(options.namespace)

  store.$database = database

  if (!store.$databases) {
    store.$databases = {}
  }

  store.$databases[database.connection] = database

  return database
}
Example #9
Source File: Store.ts    From vuex-orm-next with MIT License 6 votes vote down vote up
/**
 * Mixin Vuex ORM feature to the store.
 */
function mixin(store: Store<any>, options: FilledInstallOptions): void {
  createDatabase(store, options)

  installPlugins(store)

  mixinRepoFunction(store)

  startDatabase(store)
}
Example #10
Source File: app.ts    From vue-storefront-1 with MIT License 5 votes vote down vote up
createApp = async (ssrContext, config, storeCode = null): Promise<{app: Vue, router: VueRouter, store: Store<RootState>, initialState: RootState}> => {
  router = createRouter()
  routerProxy = createRouterProxy(router)
  // sync router with vuex 'router' store
  sync(store, routerProxy)
  // TODO: Don't mutate the state directly, use mutation instead
  store.state.version = process.env.APPVERSION
  store.state.config = config // @deprecated
  store.state.__DEMO_MODE__ = (config.demomode === true)
  if (ssrContext) {
    // @deprecated - we shouldn't share server context between requests
    Vue.prototype.$ssrRequestContext = {
      output: {
        cacheTags: ssrContext.output.cacheTags
      },
      userAgent: ssrContext.server.request.headers['user-agent']
    }

    Vue.prototype.$cacheTags = ssrContext.output.cacheTags
  }
  if (!store.state.config) store.state.config = globalConfig //  @deprecated - we should avoid the `config`
  const storeView = await prepareStoreView(storeCode) // prepare the default storeView
  store.state.storeView = storeView

  // @deprecated from 2.0
  once('__VUE_EXTEND__', () => {
    Vue.use(Vuelidate)
    Vue.use(VueLazyload, { attempt: 2, preLoad: 1.5 })
    Vue.use(Meta, {
      ssrAppId: 1
    })
    Vue.use(VueObserveVisibility)

    Object.keys(corePlugins).forEach(key => {
      Vue.use(corePlugins[key])
    })

    Object.keys(coreMixins).forEach(key => {
      Vue.mixin(coreMixins[key])
    })

    Object.keys(coreFilters).forEach(key => {
      Vue.filter(key, coreFilters[key])
    })
  })

  let vueOptions = {
    router: routerProxy,
    store,
    i18n,
    render: h => h(themeEntry)
  }

  const apolloProvider = await getApolloProvider()
  if (apolloProvider) Object.assign(vueOptions, { provider: apolloProvider })

  const app = new Vue(vueOptions)

  const appContext = {
    isServer,
    ssrContext
  }

  injectReferences(app, store, routerProxy, globalConfig)
  registerClientModules()
  registerModules(enabledModules, appContext)
  registerTheme(globalConfig.theme, app, routerProxy, store, globalConfig, ssrContext)

  await checkForIntlPolyfill(storeView)

  coreHooksExecutors.afterAppInit()
  // @deprecated from 2.0
  EventBus.$emit('application-after-init', app)

  return { app, router: routerProxy, store, initialState: stateFactory.createInitialState(store.state) }
}
Example #11
Source File: plugin.spec.ts    From vuex-orm-next with MIT License 5 votes vote down vote up
describe('feature/plugin/plugin', () => {
  it('can add extra feature to the store', async () => {
    const plugin: VuexORMPlugin = {
      install(store) {
        ;(store as any).custom = 1
      }
    }

    VuexORM.use(plugin)

    const store = new Store({
      plugins: [VuexORM.install()]
    })

    expect((store as any).custom).toBe(1)
  })

  it('can add extra feature to the components', async () => {
    const plugin: VuexORMPlugin = {
      install(_store, components) {
        ;(components.Model as any).custom = 1
      }
    }

    VuexORM.use(plugin)

    new Store({
      plugins: [VuexORM.install()]
    })

    expect((Model as any).custom).toBe(1)
  })

  it('can take options', async () => {
    const plugin: VuexORMPlugin = {
      install(store, _components, options) {
        ;(store as any).custom = options
      }
    }

    VuexORM.use(plugin, 1)

    new Store({
      plugins: [VuexORM.install()]
    })

    expect((Model as any).custom).toBe(1)
  })
})
Example #12
Source File: Helpers.ts    From vuex-orm-next with MIT License 5 votes vote down vote up
export function assertState(store: Store<any>, entities: Entities): void {
  expect(store.state.entities).toEqual(createState(entities))
}
Example #13
Source File: Helpers.ts    From vuex-orm-next with MIT License 5 votes vote down vote up
export function createStore(): Store<any> {
  return new Store({
    plugins: [VuexORM.install()],
    strict: true
  })
}
Example #14
Source File: Store.ts    From vuex-orm-next with MIT License 5 votes vote down vote up
/**
 * Start the database.
 */
function startDatabase(store: Store<any>): void {
  store.$database.start()
}
Example #15
Source File: Database.ts    From vuex-orm-next with MIT License 5 votes vote down vote up
/**
   * The store instance.
   */
  store!: Store<any>
Example #16
Source File: Database.ts    From vuex-orm-next with MIT License 5 votes vote down vote up
/**
   * Set the store.
   */
  setStore(store: Store<any>): this {
    this.store = store

    return this
  }
Example #17
Source File: modules.ts    From vue-storefront-1 with MIT License 5 votes vote down vote up
function injectReferences (app: any, store: Store<any>, router: VueRouter, config: any): void {
  refs.app = app
  refs.store = store
  refs.router = router
  refs.config = config
}
Example #18
Source File: index.ts    From vueconf-london with MIT License 5 votes vote down vote up
key: InjectionKey<Store<State>> = Symbol()
Example #19
Source File: index.ts    From vue3-cesium-typescript-start-up-template with MIT License 5 votes vote down vote up
key: InjectionKey<Store<RootState>> = Symbol()
Example #20
Source File: index.ts    From vue3-cesium-typescript-start-up-template with MIT License 5 votes vote down vote up
export function useStore(): Store<RootState> {
  return baseUseStore(key)
}
Example #21
Source File: index.ts    From Vue3-Vite-Vuetify3-Typescript-Template with MIT License 5 votes vote down vote up
key: InjectionKey<Store<storeTypes>> = Symbol()
Example #22
Source File: actions.ts    From vue3-ts-base with MIT License 5 votes vote down vote up
consoleActions = {
  // 获取用户角色列表
  async getRoleList(): Promise<HttpResponse | number> {
    const res = await CommonService.getRoleInfoList()
    if (res.status === 200) {
      const data = res.data.data
      setStoreState('console', 'roleList', data ? data : [])
      return res
    }
    return 0
  },

  // 获取团队列表
  async getTeamList(context: Store<StateType>, params: HttpListQuery): Promise<HttpResponse | number> {
    const res = await TeamService.list({ ...params })
    if (res.status === 200) {
      const data = res.data.data
      setStoreState('console', 'myTeamList', data.rows ? data.rows : [])
      return res
    }
    return 0
  },

  // 获取某个团队的所有成员信息
  async getTeamMemberList(context: Store<StateType>, id: number): Promise<HttpResponse | number> {
    const res = await TeamService.memberList(id as number)
    if (res.status === 200) {
      const memberList = res.data.data.rows.filter((item: any) => [RoleType['团队超级管理员'], RoleType['团队成员'], RoleType['团队访客'], RoleType['团队管理员']].includes(item.roleId))
      setStoreState('console', 'selectedTeamMemberList', memberList)
    }
    return 0
  },

  // 获取某个团队的详细信息
  async getTeamDetail(context: Store<StateType>, id: number): Promise<HttpResponse | number> {
    console.log('chufa')
    const res = await TeamService.detail(id)
    if (res.status === 200) {
      const data = res.data.data
      setStoreState('console', 'selectedTeam', data)
      return data
    }
    return 0
  },

  // 获取某个主账号下的所有的
  async getSubAccountList(): Promise<HttpResponse | number> {
    const res = await ManageService.getSubAccountList({
      pageSize: StaticConfig.MaxPageSize,
      pageNum: 1
    })
    if (res.status === 200) {
      const data = res.data.data.rows
      setStoreState('console', 'subAccountList', data)
      return data
    }
    return 0
  },

  // 获取当前选择团队下所有的云角色列表
  async getTeamCloudRoleList(context: Store<StateType>, teamId: number): Promise<HttpResponse | number> {
    console.log(`id=${teamId}`)
    const res = await CloudRoleService.list(teamId)
    if (res.status === 200) {
      const data = res.data.data
      console.log(data)
      setStoreState('console', 'selectedTeamCloudRoleList', data)
      return res
    }
    return 0
  }
}
Example #23
Source File: index.ts    From vue3-ts-base with MIT License 5 votes vote down vote up
key: InjectionKey<Store<StateType>> = Symbol()
Example #24
Source File: store-accessor.ts    From IYUU-GUI with GNU Affero General Public License v3.0 5 votes vote down vote up
// initializer plugin: sets up state/getters/mutations/actions for each store
export function initializeStores(store: Store<any>): void {
    IYUUStore = getModule(IYUUModule, store)
    MissionStore = getModule(MissionModule, store)
    StatusStore = getModule(StatusModule, store)
}
Example #25
Source File: index.ts    From IYUU-GUI with GNU Affero General Public License v3.0 5 votes vote down vote up
initializer = (store: Store<any>) => initializeStores(store)
Example #26
Source File: afterRegistration.ts    From vue-storefront-1 with MIT License 4 votes vote down vote up
export function afterRegistration (config, store: Store<any>) {
  if (isEnabled(config.googleTagManager.id)) {
    const GTM: VueGtm = (Vue as any).gtm

    const storeView = currentStoreView()
    const currencyCode = storeView.i18n.currencyCode

    const getProduct = (item) => {
      let product = {}

      const attributeMap: string[]|Record<string, any>[] = config.googleTagManager.product_attributes
      attributeMap.forEach(attribute => {
        const isObject = typeof attribute === 'object'
        let attributeField = isObject ? Object.keys(attribute)[0] : attribute
        let attributeName = isObject ? Object.values(attribute)[0] : attribute

        if (item.hasOwnProperty(attributeField) || product.hasOwnProperty(attributeName)) {
          const value = item[attributeField] || product[attributeName]
          if (value) {
            product[attributeName] = value
          }
        }
      })

      const { category } = item
      if (category && category.length > 0) {
        product['category'] = category.slice(-1)[0].name
      }

      return product
    }

    store.subscribe(({ type, payload }, state) => {
      // Adding a Product to a Shopping Cart
      if (type === 'cart/cart/ADD') {
        GTM.trackEvent({
          event: 'addToCart',
          ecommerce: {
            currencyCode: currencyCode,
            add: {
              products: [getProduct(payload.product)]
            }
          }
        });
      }

      // Removing a Product from a Shopping Cart
      if (type === 'cart/cart/DEL') {
        GTM.trackEvent({
          event: 'removeFromCart',
          ecommerce: {
            remove: {
              products: [getProduct(payload.product)]
            }
          }
        });
      }

      // Measuring Views of Product Details
      if (type === 'product/product/SET_PRODUCT_CURRENT') {
        GTM.trackEvent({
          ecommerce: {
            detail: {
              'actionField': { 'list': '' }, // 'detail' actions have an optional list property.
              'products': [getProduct(payload)]
            }
          }
        });
      }

      // Measuring Purchases
      if (type === 'order/orders/LAST_ORDER_CONFIRMATION') {
        const orderId = payload.confirmation.backendOrderId
        const products = payload.order.products.map(product => getProduct(product))
        store.dispatch(
          'user/getOrdersHistory',
          { refresh: true, useCache: false }
        ).then(() => {
          const orderHistory = state.user.orders_history
          const order = state.user.orders_history ? orderHistory.items.find((order) => order['entity_id'].toString() === orderId) : null
          GTM.trackEvent({
            'ecommerce': {
              'purchase': {
                'actionField': {
                  'id': orderId,
                  'affiliation': order ? order.store_name : '',
                  'revenue': order ? order.total_due : state.cart.platformTotals && state.cart.platformTotals.base_grand_total ? state.cart.platformTotals.base_grand_total : '',
                  'tax': order ? order.total_due : state.cart.platformTotals && state.cart.platformTotals.base_tax_amount ? state.cart.platformTotals.base_tax_amount : '',
                  'shipping': order ? order.total_due : state.cart.platformTotals && state.cart.platformTotals.base_shipping_amount ? state.cart.platformTotals.base_shipping_amount : '',
                  'coupon': ''
                },
                'products': products
              }
            }
          })
        })
      }
    })
  }
}
Example #27
Source File: store.ts    From vscode-todo-md with MIT License 4 votes vote down vote up
store = new Store({
	// strict: isDev,
	state: {
		tasksAsTree: [] as TheTask[],
		tags: [] as string[],
		projects: [] as string[],
		contexts: [] as string[],
		defaultFileSpecified: true,
		activeDocumentOpened: false,
		filterInputValue: '',
		config: {
			autoShowSuggest: true,
			showCompleted: true,
			showRecurringCompleted: true,
			showRecurringUpcoming: true,
			completedStrikeThrough: false,
			showPriority: true,
			showCheckbox: true,
			fontSize: '13px',
			padding: '0px',
			customCheckboxEnabled: false,
			notificationsEnabled: false,
			showTaskDetails: false,
			fontFamily: `'Segoe UI', Tahoma, Geneva, Verdana, sans-serif, 'Segoe UI Emoji'`,
			indentSize: '1.8em',
			tagStyles: {},
			lineHeight: 1.4,
		} as ExtensionConfig['webview'],
		selectedTaskLineNumber: -1,
	},
	getters: {
		filteredSortedTasks: state => {
			let filteredTasks = state.tasksAsTree;
			if (state.filterInputValue !== '') {
				filteredTasks = filterItems(filteredTasks, state.filterInputValue || '');
			}
			if (!state.config.showRecurringCompleted) {
				filteredTasks = filteredTasks.filter(task => {
					if (task.due?.isRecurring && task.done) {
						return false;
					} else {
						return true;
					}
				});
			}
			if (!state.config.showRecurringUpcoming) {
				filteredTasks = filteredTasks.filter(task => {
					if (task.due?.isRecurring && task.due.isDue === DueState.NotDue) {
						return false;
					} else {
						return true;
					}
				});
			}
			if (!state.config.showCompleted) {
				filteredTasks = filteredTasks.filter(task => !task.done);
			}
			return defaultSortTasks(filteredTasks);
		},
		flattenedFilteredSortedTasks: (state, getters) => flattenDeep(getters.filteredSortedTasks),
		autocompleteItems: state => {
			const filterConstants = [// TODO: constants should be in const enum
				'$due',
				'$started',
				'$hasDue',
				'$done',
				'$overdue',
				'$recurring',
				'$noTag',
				'$noProject',
				'$noContext',
			];
			const autocompleteTags = state.tags.map(tag => `#${tag}`);
			const autocompleteProjects = state.projects.map(project => `+${project}`);
			const autocompleteContexts = state.contexts.map(context => `@${context}`);
			return [{
				data: filterConstants.concat(autocompleteTags, autocompleteProjects, autocompleteContexts),
			}];
		},
	},
	mutations: {
		[Mutation.SELECT_TASK]: (state, lineNumber: number) => {
			state.selectedTaskLineNumber = lineNumber;
		},
		[Mutation.UPDATE_FILTER_VALUE]: (state, newValue: string) => {
			state.filterInputValue = newValue;
		},
		[Mutation.TOGGLE_DONE]: (state, task: TheTask) => {
			task.done = !task.done;
		},
	},
	actions: {
		[Action.SELECT_NEXT_TASK]({ commit, state, getters: gt }) {
			const getters = gt as Getters;
			if (!getters.filteredSortedTasks.length) {
				return undefined;
			}
			let targetTask: TheTask;
			if (state.selectedTaskLineNumber === -1) {
				// None selected. Select the first visible task
				targetTask = getters.filteredSortedTasks[0];
			} else {
				// Selected task exists
				const selectedTask = getTaskAtLineWebview(state.selectedTaskLineNumber);

				if (!selectedTask) {
					return undefined;
				}

				const tasks = getters.flattenedFilteredSortedTasks.filter(task => isTaskVisible(task));
				if (tasks.length < 2) {
					return undefined;
				}

				const currentIndex = tasks.findIndex(task => selectedTask.lineNumber === task.lineNumber);
				targetTask = currentIndex === tasks.length - 1 ? tasks[0] : tasks[currentIndex + 1];
			}
			selectTaskMutation(targetTask.lineNumber);
			return targetTask.lineNumber;
		},
		[Action.SELECT_PREV_TASK]({ commit, state, getters: gt }) {
			const getters = gt as Getters;
			if (!getters.filteredSortedTasks.length) {
				return undefined;
			}
			let targetTask: TheTask;
			if (state.selectedTaskLineNumber === -1) {
				// None selected. Select the first visible task
				targetTask = getters.flattenedFilteredSortedTasks[getters.flattenedFilteredSortedTasks.length - 1];
			} else {
				const selectedTask = getTaskAtLineWebview(state.selectedTaskLineNumber);
				if (!selectedTask) {
					return undefined;
				}

				const tasks = getters.flattenedFilteredSortedTasks.filter(task => isTaskVisible(task));

				if (tasks.length < 2) {
					return undefined;
				}

				const currentIndex = tasks.findIndex(task => selectedTask.lineNumber === task.lineNumber);
				if (currentIndex === 0) {
					targetTask = tasks[tasks.length - 1];
				} else {
					targetTask = tasks[currentIndex - 1];
				}
			}
			selectTaskMutation(targetTask.lineNumber);
			return targetTask.lineNumber;
		},
	},
})