Issues with managing stages in Typescript using Quasar and Vue are obstructing progress

I'm completely new to working with vuex and I'm facing some challenges in getting it set up properly. Here is the current structure of my store folder:

  • store
  • module-example
    • index.ts
    • mutations.ts
    • getters.ts
    • state.ts
  • index.ts
  • store-flag.d.ts

The file contents are as follows:

index.ts

import { store } from 'quasar/wrappers';
import Vuex from 'vuex';

import example from './module-example';

export interface StateInterface {
  example: unknown;
}

export default store(function ({ Vue }) {
  Vue.use(Vuex);

  const Store = new Vuex.Store<StateInterface>({
    modules: {
     example
    },
    strict: !!process.env.DEBUGGING
  });

  if (process.env.DEV && module.hot) {
    module.hot.accept(['./showcase'], () => {
      const newShowcase = require('./showcase').default
      Store.hotUpdate({ modules: { showcase: newShowcase } })
    })
  }

  return Store;
});

store-flag.d.ts

/* eslint-disable */
import "quasar/dist/types/feature-flag";

declare module "quasar/dist/types/feature-flag" {
  interface QuasarFeatureFlags {
    store: true;
  }
}

index.ts

import { Module } from 'vuex';
import { StateInterface } from '../index';
import state, { ExampleStateInterface } from './state';
import getters from './getters';
import mutations from './mutations';

const exampleModule: Module<ExampleStateInterface, StateInterface> = {
  namespaced: true,
  getters,
  mutations,
  state
};

export default exampleModule;

mutations.ts

import { MutationTree } from 'vuex';
import state, { ExampleStateInterface } from './state';

const mutation: MutationTree<ExampleStateInterface> = {
  someMutation (state: ExampleStateInterface, token: ExampleStateInterface) {
    state = token
  }
};

export default mutation;

getters.ts

import { GetterTree } from 'vuex';
import { StateInterface } from '../index';
import { ExampleStateInterface } from './state';

const getters: GetterTree<ExampleStateInterface, StateInterface> = {
  getToken (state: ExampleStateInterface): string {
    return state.token
  },
  getUserName (state: ExampleStateInterface): string {
    return state.username
  },
  getRetrievalTime (state: ExampleStateInterface): Date {
    return state.retrievalTime
  }
};

export default getters;

state.ts

export interface ExampleStateInterface {
  token: string;
  username: string;
  retrievalTime: Date;
}

function state(): ExampleStateInterface {
  return { token:'dddddd', username: 'ddd', retrievalTime: new Date() }
};

export default state;

Currently, I'm able to access the state using the following code:

console.log(this.$store.state.example.retrievalTime)

But, I'm encountering an error because the type is set to any. Additionally, I'm facing issues with performing mutations. I have tried the following code but it doesn't seem to have any effect:

this.$store.commit('example/someMutation', { token:'new', username: 'new', retrievalTime: new Date() })

I've searched online for examples specifically related to quasar in typescript, but I haven't found anything that works. Any help or suggestions would be greatly appreciated.

Answer №1

Although this question was asked 8 months ago, I wanted to share my solution for working with Vuex in Quasar with TypeScript, utilizing the new Composition API:

The Vue file/page structure is quite simple and straightforward:

Here is an example of a Vue file named MyVuePage.vue:

<template>
  <q-page padding>
    <!-- content -->
    <p>This is the survival page.</p>
    <p>This is my counter: {{ counter }}</p>
    <q-btn color="primary" label="Increment" @click="addToCounter(3)" />
  </q-page>
</template>

<script>
import { defineComponent, computed } from 'vue';
import { useStore } from 'src/store';

export default defineComponent({
  name: 'Survival',
  setup() {
    const store = useStore();

    // store.getters['example/counter']
    // void store.commit('example/increment', val)

    return {
      counter: computed(() => store.state.example.counter),
      addToCounter: (val) => void store.dispatch('example/increment', val),
    };
  },
});
</script>

I made modifications to the index.ts file in the default Quasar store folder to incorporate TypeScript types and organize single store files instead of separate ones for each call (getters, mutations, etc). To create a new store, simply add it to a subfolder named 'stores', import it along with its interface (such as the 'example' store), and export the interface and module as shown below:

Here is an example modification to store/index.ts:

import { store } from 'quasar/wrappers';
import { InjectionKey } from 'vue';
import {
  createStore,
  Store as VuexStore,
  useStore as vuexUseStore,
} from 'vuex';

import example, { ExampleStateInterface } from './stores/example';

// Other code here...

export interface StateInterface {
  example: ExampleStateInterface;
}

// Additional code here...

To ensure this code functions properly, make sure to update your store file in the 'stores' subfolder with a structure like the one provided below:

Example code for store/stores/example.ts:

import { Module } from 'vuex';
import { GetterTree, MutationTree, ActionTree } from 'vuex';
import { StateInterface } from '../index';

// Code structure for example store...

export default exampleModule;

By following these steps, you can seamlessly integrate Vuex 4.x with Quasar 2.4 using the powerful Composition API with TypeScript support up to your Vue page for state objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...

What are some methods for utilizing the "name" attribute within React components?

About My Coding Environment Utilizing TypeScript and ReactJS The Issue with Using name as an Attribute Encountering the following error: Type '{ name: string; "data-id": string; "data-type": string; }' is not assignable to ...

Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data. <v-row> <!-- Breadcrumbs --> <v-col class="d-flex"> <v-breadcrumbs :items="breadcrumbs"></v ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

What is the process for programmatically incorporating Vue 3 components?

Vue 3 no longer includes the Vue.extend() method, which means the example provided in this article won't work as intended: https://css-tricks.com/creating-vue-js-component-instances-programmatically/ I attempted to implement a solution from: https:// ...

Is it feasible to incorporate a multi-level navigation menu into the "NavItem" component using MaterialUI with TypeScript?

Instructions for creating a multi-level navigation menu using MaterialUI and TypeScript: To the existing '/questions' section, it is desired to include the following 2 navigation menus: /questions/Tags /questions/Users This should resemble the ...

The issue of a mocked MobX store in Jest not resetting between tests is causing problems

I have a straightforward login component and a MobX store that holds user information. I am testing the integration using Jest. The application is built with Create React App, so my tests are based on that. This is what my Login component looks like: cons ...

Is there a way to identify the accurate or incorrect array element and modify the component color accordingly?

Upon reviewing the question alternatives, I encountered a problem where clicking on one of the buttons correctly indicated whether it was the correct or incorrect answer by changing its color. However, the issue is that all buttons are being affected by th ...

Issue with using third-party package types in Angular library creation

My project involves creating a custom voice recognition library, and I have decided to utilize 3rd party package types called @types/dom-speech-recognition. However, upon attempting to integrate these types into my service, the compiler raised errors indic ...

What is the best way to filter by enum value in Typescript?

If I define an enum as follows: export enum Status { InProgress = 0, Completed = 1, Cancelled = 2 } and have a class that references the enum: import { Status } from "./Status"; export class TaskDto { public name: string = null; public c ...

Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks! Update: I want to simplify my code and avoid using app.get(...) Here's my code snippet ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

Exporting a value from a class in Angular 2 using TypeScript

import {TranslateService, LangChangeEvent} from "@ngx-translate/core"; class CustomLanguageExporter { public currentLang : string; constructor(private translate : TranslateService) { } public static setLanguage(): string { this.tr ...

Having trouble retrieving image information within the Asp.net core controller

I am facing an issue trying to store image details in the database through Angular and ASP.NET Core. I am unable to retrieve the image data sent from Angular in the controller. Although I am able to obtain the image information using the [FromForm] attribu ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first. Is there a way to automatically trigger another observable when a specific ...

Function not functioning as expected in NestJS MongoDB unique field feature

I am trying to set the "unique:true" attribute for the name property in my NestJS - MongoDB schema, but it is not working as expected by default. @Schema() export class User { @Prop() userId:string; @Prop({ type:String, required:true, } ...