我目前正在开发我的第一个vue应用程序,目前正在构建登录逻辑.

import { defineStore } from "pinia";

export const useLoginStatusStore = defineStore('loginStatus', {
    id: 'loginStatus',
    state: () => ({
        isLoggedIn: false
    }),
    actions: {
        logIn() {
            this.isLoggedIn = true
            console.log("Login", this.isLoggedIn)
        },
        logOut() {
            this.isLoggedIn = false
            console.log("Logout", this.isLoggedIn)
        }
    }
})

到目前为止,一切正常,我可以访问组件和路由文件中的状态和操作.

**<roouter.js>**

import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'
import { createApp, ref } from 'vue'
import { useLoginStatusStore } from '../stores/loginStatus.js'

import App from '../App.vue'
import WelcomeView from '../views/public/WelcomeView.vue'
import SplashView from '../views/public/SplashView.vue'

const pinia = createPinia()
const app = createApp(App)
app.use(pinia)

const loginStatusStore = useLoginStatusStore()
let isLoggedIn = ref(loginStatusStore.isLoggedIn)

console.log("isLoggedIn", loginStatusStore.isLoggedIn)


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'splash',
      component: SplashView
    },
    {
      path: '/welcome',
      name: 'welcome',
      component: WelcomeView
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/public/LoginView.vue')
    },
    {
      path: '/signup',
      name: 'signup',
      component: () => import('../views/public/SignUpView.vue')
    },
    {
      path: '/resetpassword',
      name: 'resetpassword',
      component: () => import('../views/public/ForgotPasswordView.vue')
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/protected/HomeView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/sounds',
      name: 'sounds',
      component: () => import('../views/protected/SoundsView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/player',
      name: 'soundPlayer',
      component: () => import('../views/protected/SoundPlayerView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/protected/ProfileView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/meditation',
      name: 'meditation',
      component: () => import('../views/protected/MeditationView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/tools',
      name: 'tools',
      component: () => import('../views/protected/ToolsView.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    console.log("Router", isLoggedIn.value)
    if (!isLoggedIn.value) {
      next({
        name: 'welcome'
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router

在路由中,它被用于受保护的路由和应用程序中.vue用于条件类呈现.

问题是,当状态更新时,组件中的状态不会更新,组件本身也不会更新.我在piniatry 了$subscribe方法,但没有成功.我知道,我们需要的是能产生react 性的东西.但不知道该怎么做.我非常感谢您在这方面的帮助:)

谢谢你的阅读

**App.vue**

<script setup>
import { RouterView } from 'vue-router';
import DevNavItem from '@/components/header/DevNavItem.vue'
import HeaderItem from '@/components/header/HeaderItem.vue'
import FooterItem from '@/components/footer/FooterItem.vue'
import { useLoginStatusStore } from './stores/loginStatus.js';

const loginStatusStore = useLoginStatusStore()
const isLoggedIn = loginStatusStore.isLoggedIn

console.log("App.vue", loginStatusStore.isLoggedIn)

</script>

<template>
  <DevNavItem />
  <HeaderItem v-if="isLoggedIn" />
  <RouterView :class="isLoggedIn ? 'mainProtected' : 'mainPublic'" />
  <FooterItem v-if="isLoggedIn" />
</template>

<style>
/*FONT-IMPORT*/
@import url("@/assets/font/alegreya_font.scss");

/* GENERAL STYLES */

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
header {
  position: top;
}
.mainProtected {
  width: 100vw;
  height: 83vh;
  overflow: hidden;
}
.mainPublic {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

/* GLOBAL CLASSES */

.mainLogo {
  height: 350px;
  width: 350px;
  background: url("./img/icons/main.png") center/cover no-repeat;
}
.leavesBackground {
  background-color: #253334;
  background-image: url("./src/img/images/background_partial.png");
  background-repeat: no-repeat;
  background-position: bottom;
  background-size: contain;
}
.logoSmall {
  background: url("./img/icons/main.png") center/contain no-repeat;
  height: 100px;
  width: 100px;
}
.buttonPublic {
  padding: 20px 0;
  text-align: center;
  background-color: #7c9a92;
  color: #fff;
  border-radius: 15px;
  width: 90%;
  text-decoration: none;
  font-size: 24px;
  border: none;
}
</style>

我试着用$subscribe订阅这个州,但没有成功.

推荐答案

storeToRefs()

您需要使用100从存储中提取属性,同时保持其react 性.

import { storeToRefs } from 'pinia'
const themeStore = useThemeStore();
const { isDark } = storeToRefs(themeStore);

从store 获取react 状态的错误方法:

下面我列出的从Piniastore 获得state(属性、getter)的所有方法都是wrong:

// WRONG ways of extracting state from store
import { useThemeStore } from "./stores/theme.js";
const themeStore = useThemeStore();
let isDark = themeStore.isDark; // not reactive
let isDark = ref(themeStore.isDark); // not reactive
let { isDark } = themeSore; // not reactive, cannot destructure

Destructuring actions directly from the store.

这里值得注意的是,"你可以直接从store 中解构操作,因为它们绑定到store 本身."(docs)

如果存储中有一个名为"increment"的操作,您可以直接从组件中的存储中提取它:

...
const { increment } = store // actions can be destructured directly
...

此外,根据Pinia docs,第一个参数是unique ID,因此不需要在options对象中再次指定id.或者可以忽略第一个参数,只指定id作为选项.两种方式都可以.

Javascript相关问答推荐

响应式JS DataTable中的Bootstrap 5弹出程序无法正常工作

带对角线分隔符的图像滑动器

想要检测字符串中的所有单词

为什么使用MAX_SAFE_INTEGER生成随机整数时数字分布不准确?

序列查找器功能应用默认值而不是读取响应

ReactJS中的material UI自动完成类别

类型自定义lazy Promise. all

在观察框架中搜索CSV数据

Angular 中的类型错误上不存在获取属性

无法使用单击按钮时的useState将数据从一个页面传递到另一个页面

使用原型判断对象是否为类的实例

如何强制Sphinx中的自定义js/css文件始终加载更改而不缓存?

Reaction组件在本应被设置隐藏时仍显示

输入的值的类型脚本array.排序()

在渲染turbo流之后滚动到元素

JavaScript&;Reaction-如何避免在不使用字典/对象的情况下出现地狱?

JavaScript -复制到剪贴板在Windows计算机上无效

按特定顺序将4个数组组合在一起,按ID分组

如何使用Reaction路由导航测试挂钩?

表单数据中未定义的数组键