vue.js - 使用 vuex 确保存储状态中存在变量
问题描述
仅当我有用户详细信息时,我才限制我的应用程序加载到 DOM:
<template>
<div id="app">
<template v-if="loggedUser">
//...
</template>
</div>
</template>
loggedUser
商店的计算属性在哪里:
computed: {
loggedUser() {
return this.$store.getters.user;
}
}
问题是其他组件依赖于现有的这个属性。例如,在一个名为 admin 的组件中/admin
,当mounted()
我将用户对象从 store 传递给一个方法时,该方法又执行 HTTP 请求:
mounted(){
this.someFunc(this.$store.getters.user)
}
但问题是有时用户存在,有时用户不存在。如果用户尝试直接从管理页面加载应用程序并且用户不存在,则这是真的。解决此问题的一种可能选择是使用watch
从商店返回用户的计算属性:
computed: {
user() {
return this.$store.getters.user;
}
},
watch: {
user(newVal) {
if(newVal) this.someFunc(this.$store.getters.user)
}
}
虽然这可能有效,但即使对于这个例子来说也感觉很乏味。然而,由于这个问题,出现了更大更复杂的问题。另一个可能的选择是尝试将用户保存在 localStorage 中,但我猜 vuex 应该能够在不使用任何类型的客户端存储解决方案的情况下解决我的问题。知道如何解决这个问题吗?是否有更强大的方法来确保用户在我的整个应用程序中都可用?
解决方案
如果您使用 vue 路由器,您可以在那里对用户进行身份验证:
const ifAuthenticated = (to, from, next) => {
if (store.state.token) { // or state.user etc.
next()
return
}
next('/Adminlogin') // if not authenticated
路由器路径如下所示:
{
path: '/AdminUI',
name: 'AdminUI',
component: AdminUI,
beforeEnter: ifAuthenticated
}
另一种可能的解决方案:
<v-template
v-show="$store.state.isUserLoggedIn"
</v-template>
不要忘记import { mapState } from "vuex";
并在store
:
getters: {
isUserLoggedIn: state => !!state.token
}
推荐阅读
- typescript - Vue js,使用 TypeScript 从 Vue 中的表单获取数据
- javascript - 从数组创建对象并将这些对象收集到一个数组中
- .net - Visual Studio - 在 MacOs 中将 Nuget 包添加到项目时,拒绝访问路径“/Users/.local/share/NuGet”
- python - 我有一个基于 4 个值的动态 xpath,如果我使用 OR 条件,xpath 看起来很大,还有其他处理方法吗?
- ios - 如何在 iOS 中为 WKWebView 启用 GamePad 功能?
- xamarin.forms - 使用 xamarin.forms 为 android 和 ios 的警报消息设置自定义字体
- c# - C# 用一个属性满足两个接口的成员
- flutter - 当Inner ScrollView到达Bottom-Flutter时如何滚动BottomNavigationBar
- python - 为函数上的变量分配不同的索引
- reactjs - 如何解决“无法更新状态”