首页 > 解决方案 > 使用 :key 在组件上绑定全局变量

问题描述

我在一个Vue项目上工作,我有一个登录页面,当用户登录时重定向到主页。

问题是当用户在主页上时,我需要更新/重新呈现标题组件。

所以我在 main.ts 中创建了一个全局变量:

Main.ts

Vue.prototype.isLogin = false;

我使用这个全局值作为我的标题的键:

应用程序.vue

<template>
  <div id="app" class="container">
    <e-header v-bind:key="isLogin" />
    <div class="alert-box">
      <div class="alert-list">
        <e-alert
          v-for="(notif, index) in $store.state.notifications"
          :key="index"
          :type="notif.type"
          @dismissAlert="dismissAlert(index)"
        >
          {{ notif.message }}
        </e-alert>
      </div>
    </div>
    <router-view />
  </div>
</template>

在登录组件上,在我的login()方法中:

登录.vue

        AdminApi.login(this.email, this.password).then(() => {
          this.loaderActive = false;
          this.isLogin = true;
        });

问题是当用户成功登录并在主页上重定向时,标题组件没有更新,我是否需要使用prop而不是我的全局变量App.vue

标签: javascriptvue.jsvue-component

解决方案


当 Vue 检测到它依赖的数据发生变化时,它会更新它。为了让 Vue 检测到它的变化,数据需要是响应式的。

原型链上的东西不是,我认为你通过使用原型链使事情变得过于复杂。要管理全局状态,只需使用 Vuex 存储。(文档

然后你可以...mapGetters(['isLoggedIn'])在你的computed属性中使用,this.$store.commit('loggedIn', true)或者在你的 Login.vue 文件中使用类似的东西。


推荐阅读