Search code examples
typescriptformsvue.jsstoreonsubmit

How can I call a method from onSubmit functon in Vue?


I have a button that is used to log in the user via onSubmit function when a form is filled in. However, I need to call yet another method that will get some additional data about the user, such as privileges. However I cannot make it to work. I've tried to put the code from desired method directly in the onSubmit() function, but it did not work. Here is my code:

This 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 my script.

<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:{
        //This did not work. useStore could not be accessed from "methods" but could be accessed from setup/mounted. 
        //The thing is, it must be updated only after clickig on the submit button. 
        setUserState(){
            const store = useStore();
            store.dispatch("setActiveUser");
        },

    }
})
</script>

Solution

  • I now found the solution to my problem. I moved setUserState() as a function under setup() and deleted the methods. Setup is setting up the store now and returns setUserState. Following code 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: "",
        });
    
        //Calls the login function in user.ts
        function onSubmit() {
          userStore.login(form.username, form.password);
          form.username = "";
          form.password = "";
    
          setUserState()
        }
    
        function setUserState(){
          store.dispatch("setActiveUser");
        }
    
            //Returns the store in the main so that the form can have a template that displays the error message.
        return {form, userStore, onSubmit, setUserState}
        },
    })
    </script>