javascript - 使用 :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
?
解决方案
当 Vue 检测到它依赖的数据发生变化时,它会更新它。为了让 Vue 检测到它的变化,数据需要是响应式的。
原型链上的东西不是,我认为你通过使用原型链使事情变得过于复杂。要管理全局状态,只需使用 Vuex 存储。(文档)
然后你可以...mapGetters(['isLoggedIn'])
在你的computed
属性中使用,this.$store.commit('loggedIn', true)
或者在你的 Login.vue 文件中使用类似的东西。
推荐阅读
- mysql - SQL获取具有特定时间段的连续开始和结束日期
- azure-web-app-service - 在 asp.net 核心中使用 Rotitiva 部署到天蓝色时显示框而不是字体的 PDF 报告
- qt - 关于 qt5 中的虚拟键盘与 windows 上的小部件应用程序
- mongodb - 如何根据日期范围 mongoDB 选择所有数据?
- xml - 为什么 XML 属性支持“>”(大于符号)而“<”(小于符号)不支持?
- maven - Maven 发布插件 - 如何仅发布快照?
- php - 如何在 PHP 中获取数组的参数
- c# - 如何获取动态文本框值c#?
- c - signal.h 中的信号宏是类对象宏还是类函数宏?
- javascript - 如何从下面的数组列表中读取每个奇数值: