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

Struggling with the transformation: Failed to find import "child_process" in TypeScript

I encountered an issue when trying to run my simple TypeScript project. I am receiving the following error: 'Error while transforming Could not resolve import "child_process".' You can see the error in this screenshot. This error occurs in my tsc ...

Attempting to access the second "th" element within a table by utilizing Vue 3 template within Cypress

While conducting my cypress test, I am attempting to access the second element in a table from the Vue template: <template> <table id="table" class="table" data-cy="table"> <thead class="table-head&qu ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...

The pipe operator in Angular is failing to function as intended

I encountered an error while using the replace operator in Angular. Can someone help me identify the issue? Check out this link for more information ...

Issues with the Web Share API navigator.share feature arise when users choose to cancel the share dialog on both IOS

Encountering a surprise error when utilizing MOBILE SHARE (navigator.share) that appears after cancelling the share flow. Although users can acknowledge the message and proceed, this unexpected error response occurs. STEPS TO REPLICATE 1. Tap the SHARE i ...

Utilize the nests cli swagger plugin to enable compatibility with external models

Exploring the functionality of the swagger plugin provided by nestjs, I am eager to try it out. While it works smoothly when defining a class like CreateUserDto, my goal is to incorporate types from a third-party library - specifically @adyen/api-library. ...

Retrieve the HTML data and save it as page.html, displayed in a VueJS preview

After developing an innovative VueJS-based application for managing front-end content, I am now eager to enhance it with a 'download' button feature. This new functionality will allow users to easily download the previewed and edited content in H ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Vue encounters an issue when trying to access a specific field within an array of objects

Consider the following data structure: rules:[ 0:{ subrule1:'', subrule2:'', subrule3:'' }, 1:{ subrule1:'', subrule2:'', subrule3:'' } ...

Every time you attempt to download in Vue, you are met with the familiar sight

Encountering a peculiar issue while attempting to download an apk file using a Vue.js website: Referring to How to download a locally stored file in VueJS, I am trying to download a local file with this command: <a href="../../app-debug.apk" download= ...

How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method? I would like to link an array to an observable, and update the array as well as have the observable monitor the changes. If this approach is feasible, how can we inco ...

Unusual behavior when importing in Angular 2 using TypeScript

While working on a demo for another question on Stack Overflow, I initially used angular-cli and then switched to Plunker. I noticed a peculiar difference in behavior with the import statement between the two setups. The issue arises with the second impo ...

React: detect the key pressed when submitting a form

I am currently working with React in combination with Material UI. My goal is to implement a functionality where the form submission only occurs when I click the Submit button, rather than triggering it by pressing enter while focused on a text field. Her ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

Struggling to understand how to properly 'map' my data from the response in Next.js 13 using Typescript

Just a few days into my journey with next.js, and I'm already facing a challenge in figuring out how to fetch data from an API. In regular React, I would typically use useState and useEffect for managing state and fetching data. But when it comes to n ...

What is the best way to use an Observable to interrogate a fork/join operation?

I have a forkjoin set up to check for the presence of a person in two different data stores. If the person is not found in either store, I want to perform a delete action which should return true if successful, and false otherwise. However, my current impl ...

Problem encountered in a simple Jest unit test - Unexpected identifier: _Object$defineProperty from babel-runtime

Struggling with a basic initial test in enzyme and Jest during unit testing. The "renders without crashing" test is failing, as depicted here: https://i.stack.imgur.com/5LvSG.png Tried various solutions like: "exclude": "/node_modules/" in tsconfig "t ...

Bootstrap Table Vue Selection

When I attempt to use the data provided below, the first column shows as true/false instead of a checkbox. Below is the Vue table code: <b-table id="myTabel" hover striped :items="tableData" :fields="tableColumns"> <template slot="selected" sl ...

Error: The module could not be located due to the inability to resolve the path to './router'. This issue is specifically related to Vue router

Looking at the search.js file: import {createRouter, createWebHistory} from "vue-router"; import SearchIndex from './components/omdb/SearchIndex.vue' const routes = [ { path: '/', name: 'welcome&apos ...