程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何从 Vue 中的 onSubmit 函数调用方法?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何从 Vue 中的 onSubmit 函数调用方法??

开发过程中遇到如何从 Vue 中的 onSubmit 函数调用方法?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何从 Vue 中的 onSubmit 函数调用方法?的解决方法建议,希望对你解决如何从 Vue 中的 onSubmit 函数调用方法?有所启发或帮助;

我有一个按钮,用于在填写表单时通过 onsubmit 函数登录用户。但是,我需要调用另一个方法来获取有关用户的一些附加数据,例如权限。但是我无法让它工作。我试图将所需方法的代码直接放在 onsubmit() 函数中,但没有奏效。这是我的代码:

这是按钮所在的表单。

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

这是我的脚本。

<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>

解决方法

我现在找到了解决问题的方法。我将 setUserState() 作为 setup() 下的函数移动并删除了这些方法。安装程序现在正在设置商店并返回 setUserState。以下代码有效:

<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>

大佬总结

以上是大佬教程为你收集整理的如何从 Vue 中的 onSubmit 函数调用方法?全部内容,希望文章能够帮你解决如何从 Vue 中的 onSubmit 函数调用方法?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。