Exploring the power of Vue 3 and Vuex with Typescript to access class methods

Can Vuex state be used to access class methods?

For example, in this scenario, I am attempting to invoke fullName() to show the user's formatted name.

TypeError: store.state.user.fullName is not a function

Classes

export class User {
    constructor(
        public id: string = '',
        public first_name: string = '',
        public last_name: string = '',
    ) {}

    fullName = (format: 'forward' | 'reverse' = 'forward') => {
        if (format === 'forward') return `${this.first_name} ${this.last_name}`
        if (format === 'reverse') return `${this.last_name}, ${this.first_name}`
    }
}
export interface RootState {
    user: User
}

Vuex

export const key: InjectionKey<Store<RootState>> = Symbol()

export default createStore<RootState>({
    strict: true,
    state: {
        user: new User(),
    },
})

Component

setup(){
    const state = useState(key)
    return {
        name: computed(_ => store.state.user.fullName('forward'))
    }
}

Answer №1

It appears that Vuex removes class methods and only retains plain values.

To address this issue, I devised a solution by creating a new instance of User and copying the Vuex User state into it.

const user = computed(_ => Object.assign(new User(), store.state.user))

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

Angular 2 Integration for Slick Carousel

Greetings! I have recently ventured into Angular 2 and am currently attempting to get a carousel plugin called slick up and running. After some trial and error, I have successfully implemented it as a Component in the following manner: import { Component ...

AngularJS date formatting fails to properly format dates

{{ map.thedate }} The result is 2014-06-29 16:43:48 Even after using the following code, it still displays the same date as above. {{ map.thedate | date:'medium' }} ...

Incorporating TypeScript into a React-Native Expo development venture

While attempting to integrate TypeScript into a React-Native Expo project, I encountered an error when renaming a file from abc.js to abc.tsx: I have been following the instructions provided at: https://facebook.github.io/react-native/blog/2018/05/07/u ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

Rendering Koa without the need for a template engine

Currently, I am in the process of practicing my skills with Node.js and have made the decision to begin with Vue + Koa. Upon studying Vue, I have come to the realization that perhaps using a template engine is unnecessary. Instead, I can simply respond wi ...

Improving Three.js performance for a single, substantial model

I am currently developing a hybrid file browser and 3D model viewer. My goal is to seamlessly load models of various formats, specifically .OBJ files, into the scene while maintaining a smooth framerate with the help of orbitControls.js. Most of the optim ...

Customize cursor using CSS

I have a div with overflow: hidden that I am making scrollable by allowing the user to click and drag the background. There are links and buttons within this space. Here is the CSS I am using for this: #div-grabscroll { cursor: url(../img/op ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

The recent update from Angular version 5.2 to 7 has caused issues with Post methods

An issue has occurred with the type mismatch in the error handling function. It seems that the argument provided is not compatible with the expected parameter type within the Observable structure. GetFullAddress(addressModel: FullAddr ...

Tips for Managing the Hardware Back Button in Ionic 3

Can someone help me enable the hardware back button in Ionic 3? I want it to redirect to specific pages and display designated content. Being new to Ionic 3, I need guidance on how to set up the hardware device buttons for redirection. ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

The best practices for managing item spacing in React or React Native

I am facing some challenges while trying to adjust the spacing of my components. My goal is to have the grid occupy 90% of the screen, with the gear icon taking up the remaining 10% <View style={{ paddingLeft: insets.left, padding ...

Is there a way to retrieve data from both JSON and a file simultaneously?

I'm trying to use JavaScript fetch API to upload a photo message with text to Discord webhook. How can I upload both my JSON data and file? var discordWebHookBody = new FormData() discordWebHookBody.append("map", map) discordWebHookBody.appe ...

Issue: `Alert` not triggering after clicking on anchor link in AJAX response

Below is the code I am currently working with: $('.ver').click(function(e) { e.preventDefault(); var id = $(this).next().val(); $.post('cotizar_detalles.php', {'id': id}) .done(function(response) { ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

What is the best approach to transform a lengthy collection of 'watch' statements into a functioning solution using VueJS?

I am new to vueJS and need some help with optimizing my code. I have a long list of watch functions that are all essentially the same, but I'm not sure how to convert them into a more efficient and functional approach. These watch functions are all r ...

When CSS is modified by inserting an extra div, it causes the positioning of other elements to shift towards

I'm currently working on adapting a method to make elements "sticky" for older browsers as discussed in this particular article. The basic idea involves implementing some JavaScript code that listens for scroll events. Upon detection of such an event ...

Endless jasmine timeout

This question is a continuation of a discussion on the Remove timeout for single jasmine spec GitHub issue. Query: Can a single test be configured to never time out? The Issue: While it's possible to set a global timeout value using DEFAULT_TIMEOU ...

Verify if the connection to MongoDB Atlas has been established for MongoDB

When working with MongoDB, I find myself switching between a local database during development and MongoDB Atlas in production. My goal is to implement an efficient text search method that utilizes $search when connected to MongoDB Atlas, and $text when co ...

Ways to prevent a particular link from functioning in HTML or JavaScript

Hey there, I am currently using a Gchat voice and video chat script. Check out my website if you're interested. The issue I'm facing is that someone logs into my chatroom and uses this flash link to crash other users' browsers. Whenever th ...