What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in making it work. I attempted to place the code from the desired method directly inside the onSubmit() function, but it did not yield the desired results. Below is the relevant code:

Below is the form where the button is located.

<form @submit.prevent="onSubmit">
 Some code
 <button class="btn btn-success" type="submit">Log in</button>
</form>

This is the script being used.

<script lang="ts">
import {defineComponent, reactive} from 'vue'
import userStore from '../store/user'
import { useStore } from "vuex";

export default defineComponent({
  setup() {
    const form = reactive({
      username: "",
      password: "",
    });

    //Calls the login function in user.ts
    const onSubmit = () => {
      userStore.login(form.username, form.password);
      form.username = "";
      form.password = "";
    };

        //Returns the store in the main so that the form can have a template that displays the error message.
        return {form, userStore, onSubmit}
    },
    methods:{
        //Despite efforts, this section did not work as intended. The useStore method could not be accessed from "methods" but was accessible from setup/mounted. 
        //The requirement is for it to be updated only after clicking on the submit button.
        setUserState(){
            const store = useStore();
            store.dispatch("setActiveUser");
        },

    }
})
</script>

Answer №1

I have finally figured out how to solve my issue. By moving setUserState() as a function under setup() and removing the methods, I was able to get Setup to properly set up the store and return setUserState. Here is the code that now works:

<script lang="ts">
import {defineComponent, reactive} from 'vue'
import userStore from '../store/user'
import { useStore } from "vuex";

export default defineComponent({
  setup() {
    const store = useStore();
    const form = reactive({
      username: "",
      password: "",
    });

    //Trigger the login function in user.ts
    function onSubmit() {
      userStore.login(form.username, form.password);
      form.username = "";
      form.password = "";

      setUserState()
    }

    function setUserState(){
      store.dispatch("setActiveUser");
    }

        //Send back the store so that the form can display any error messages in the template.
    return {form, userStore, onSubmit, setUserState}
    },
})
</script>

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

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

How to access the ID value from the URL within a different component that was passed as a prop in

I have a scenario where I am building a reusable component with two child components in the following flow: Child Component 1 -> Parent Component -> Super Parent Main Component In the child component, I define a prop called 'url' which is ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Calls to debounced functions are postponed, with all of them running once the waiting timer is complete

Utilizing the debounce function to create a real-time search feature. Researching more on debouncing from https://css-tricks.com/debouncing-throttling-explained-examples/, it seems like the function should control the number of calls made. In my scenario ...

Substitute the values of 1 and 0 with words in the displayed table by leveraging vue

I am a beginner with vue.js. Currently, I am using the vue.js element.io framework to render a table and fetching data from an API, which is working fine. My goal now is to display text in the 'Active' field instead of just 1 or 0. In Laravel, I ...

Error encountered: The combination of NextJS and Mongoose is causing a TypeError where it is unable to read properties of undefined, specifically when trying

Versions: Next.js 14.1 React 18 I am currently developing a profile section where users can update their profile information such as username, name, and profile photo. To achieve this, I have implemented a component that contains a form (using shadcn) to ...

Visual Studio Code is not properly highlighting imports for Vue 3 using the Composition API

Upon careful examination, it is evident that the import is not highlighted despite the utilization of the component SearchBar. https://i.stack.imgur.com/G4sAm.png Various attempts have been made to rectify this issue including the installation of the Vet ...

Does installing the global npm package (@vue/cli) on Node v10.9 also automatically install Node v10.8?

This situation is quite puzzling and I have yet to find a definitive answer. It seems as though it was meant to happen this way, but it still feels odd. Here's the sequence of events: I completely removed Node from my OSX system. I then reinstalled ...

Encountered issue with accessing the Error Object in the Error Handling Middleware

Below is the custom error validation code that I have developed : .custom(async (username) => { const user = await UserModel.findOne({ username }) if (user) throw new ConflictError('username already used& ...

Adding a Row to an HTML Table Inside a Form through JavaScript

I'm currently attempting to insert a row into a table that resides within a form using JavaScript. The strange thing is, the code functions perfectly when it's placed outside of the form tags. However, as soon as I enclose the code within the for ...

Utilizing ng-click and ng-switch during the submission of an Angular form

I am working on a single-page Angular app where the landing page is a sign-in form with a link to a sign-up form. The rest of the app remains hidden until the user has been authenticated. To switch between the sign-in and sign-up pages, I am using the ng ...

Utilizing Vue3's draggable component to seamlessly incorporate items

My current project involves the use of the vue draggable package, and below you will find the complete component: <template> <div> <button class="btn btn-secondary button" @click="add">Add</button> ...

How do you effectively manage components within the Vue framework?

I'm just starting out with vue and I'm still learning how to organize things effectively. Currently, I am working on my own small project using Vue, which is a booklist app. It's similar to a basic todo app but includes additional features ...

steps to authenticate with dynamic database information instead of hard-coded data

After following a tutorial, I successfully created my first register login system in dot net and angular. The issue I encountered is that the author used static data in the tutorial's code example. However, I want to implement my own database data. As ...

Necessary form group in html [Angular]

Is there a way to make certain form fieldsets required while allowing the user to choose which inputs to fill? My idea: Users can select what they want to fill out without having to complete all of the fieldset inputs. I have these two options: 1: < ...

When a React Native TextInput is focused, it restricts the ability to press other child components

Issue with Nested TextInput component affecting onPress function of other components. Press only works when the TextInput is not in focus. React Native Version : 0.66.3 Here's the code snippet: export const Component = (props): JSX.Element { const ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Using Karma-Jasmine to Import Spy without anyImplicitAny

If I include the configuration setting noImplicitAny in the tsconfig.json file of my Angular 4+ project: "noImplicitAny": true, ...and then try to import and use Spy in a unit test: import { Spy } from "karma-jasmine"; I encounter this console error wh ...

Vue.js Element UI dialog box

Is there a method to customize the close button in el-dialog and replace it with my own design? For instance, can I change the default close button located at the top left corner of the dialog? <el-dialog title="Tips" :visible.sync=" ...