首页 > 解决方案 > 从 mixin 打开全局模态

问题描述

我创建了一个 authService mixin,以登录用户身份调用我的 api(使用其令牌)。

import ModalLogin from '@/components';

export default {
    components: {
        ModalLogin
    },
    data: function () {
        return {
        }
    },
    methods: { 
        authorizedGet(url) {
            if(!localStorage.getItem('user')) {
                ModalLogin.methods.show()
            } else {
                // ...
            }
        }
    }
}

在那个mixin中,如果用户没有通过身份验证,我想从一个组件(定义为一个全局组件)打开我的模式登录表单。

但是,当它尝试执行“show()”时,我得到:

ModalLogin 未定义

编辑:

这是我的 ModalLogin 组件:

<template>
    <!--Form modal-->
    <!-- ... -->
</template>
<script>
import User from '../models/user';

  export default {
    name: "modalLogin",
    data() {
      return {
        user: new User('', ''),
        loading: false,
        message: ''
      };
    },
    methods: {
      handleLogin() {
        this.loading = true;
        this.$validator.validateAll().then(isValid => {
            if (!isValid) {
            this.loading = false;
            return;
            }

            if (this.user.username && this.user.password) {
            this.$store.dispatch('auth/login', this.user).then(
                () => {
                this.$router.push('/profile');
                },
                error => {
                this.loading = false;
                this.message =
                    (error.response && error.response.data) ||
                    error.message ||
                    error.toString();
                }
            );
            }
        });
      },
      showModal() {
        this.$refs['login-modal'].show()
      }
    }
  }
</script>
<style>
</style>

...它被定义为更多组件的全局:

// ...
import ModalLogin from '@/components/ModalLogin.vue';
// ...
/**
 * You can register global components here and use them as a plugin in your main Vue instance
 */

const GlobalComponents = {
  install(Vue) {
    // ...
    Vue.component(ModalLogin.name, ModalLogin);
    // ...
  }
};

导出默认 GlobalComponents;

标签: javascriptvue.js

解决方案


推荐阅读