programing

getter(Vuex)에서 상태를 호출할 때 정의되지 않음

prostudy 2022. 4. 13. 21:00
반응형

getter(Vuex)에서 상태를 호출할 때 정의되지 않음

내 Vuex 저장소에 저장한 로그인 세션의 상태를 가져오려고 하지만 다음 정보를 얻으십시오.

검색되지 않은 TypeError: 정의되지 않은 속성 '사용자'를 읽을 수 없음

내 가게:

    let store = {
        state: {
            user: null
        },
        mutations: {
            setAuthUser(state, user) {
                state.user = user;
            }
        },
        getters: {
            isLoggedIn(state) {
                return state.user !== null;
            }
        }
    };
    
    export default store;

이 오류는 getter를 호출할 때 발생한다.

    let isLoggedIn = store.getters.isLoggedIn()

내 앱 js

    /**
     * First we will load all of this project's JavaScript dependencies which
     * includes Vue and other libraries. It is a great starting point when
     * building robust, powerful web applications using Vue and Laravel.
     */
    
    require('./bootstrap');
    
    window.Vue = require('vue');
    import lang from 'element-ui/lib/locale/lang/es';
    import locale from 'element-ui/lib/locale';
    locale.use(lang);
    // Importamos vue router, para la transición entre páginas.
    import VueRouter from 'vue-router'
    Vue.use(VueRouter)
    // Importamos Axios para las peticiones o llamadas.
    import axios from 'axios'
    import VueAxios from 'vue-axios'
    Vue.use(VueAxios, axios)
    // Importamos Vuevalidate, para validar obviamente.
    import Vuelidate from 'vuelidate'
    Vue.use(Vuelidate)
    // Importamos el componente que nos dara el efecto de cargar o loading
    import Loading from 'vue-loading-overlay';
    import 'vue-loading-overlay/dist/vue-loading.css';
    // Importamos el componente para las notificaciones flash
    import VueFlashMessage from 'vue-flash-message';
    Vue.use(VueFlashMessage);
    // Importamos Vuex
    import Vuex from 'vuex'
    import store from './store.js';
    Vue.use(Vuex)
    // Importamos UI Element
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI);
    // Importamos componentes internos
    import isLoggedMixin from './components/mixins/Auth.js'
    import Index from './components/Index.vue'
    import Home from './components/Home.vue'
    import Registro from './components/Auth/Registro.vue'
    import Login from './components/Auth/Login.vue'
    import Olvide from './components/Auth/Olvide.vue'
    import Reset from './components/Auth/Reset.vue'
    // Componentes de TIENDA, PAGOS...
    import ListaTienda from './components/Tienda/Lista.vue'
    import NuevaTienda from './components/Tienda/Nueva.vue'
    import NuevaTiendaPaso2 from './components/Tienda/Nueva-paso2.vue'
    import NuevaTiendaPaso3 from './components/Tienda/Nueva-paso3.vue'
    import NuevaTiendaPasoDsc from './components/Tienda/Nueva-dsc.vue'
    import NuevaTiendaPasoOse from './components/Tienda/Nueva-ose.vue'
    import Pagos from './components/Tienda/Pagos.vue'
    import Comprobante from './components/Tienda/Comprobante.vue'
    // Componentes dentro del sistema
    import InicioSistema from './components/Procesos/Inicio.vue'
    
    /**
     * The following block of code may be used to automatically register your
     * Vue components. It will recursively scan this directory for the Vue
     * components and automatically register them with their "basename".
     *
     * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
     */
    
    // const files = require.context('./', true, /\.vue$/i)
    // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
    
    //Vue.component('example-component', require('./components/ExampleComponent.vue').default);
    Vue.component('index', Index);
    Vue.component('header-component', require('./components/Header.vue').default);
    Vue.component('footer-component', require('./components/Footer.vue').default);
    Vue.component('loading', Loading);
    
    const router = new VueRouter({
        mode: 'history',
        routes: [
          {
            path: '/',
            name: 'home',
            component: Home,
            meta: { headersistema: false, }
        },
        {
          path: '/ingresar',
          name: 'ingresar',
          component: Login,
          meta: { headersistema: false, requiresAuth: false, }
      },
          {
            path: '/registro',
            name: 'registro',
            component: Registro,
            meta: { headersistema: false, requiresAuth: false, }
        },
      {
        path: '/olvide-mi-contraseña',
        name: 'olvide-mi-contraseña',
        component: Olvide,
        meta: { headersistema: false, requiresAuth: false, }
      },
      {
        path: '/restablecer/contraseña/:id',
        name: 'restablecer-contraseña',
        component: Reset,
        meta: { headersistema: false, requiresAuth: false, }
      },
      {
        path: '/tiendas',
        name: 'lista-tiendas',
        component: ListaTienda,
        meta: { headersistema: false, requiresAuth: true, }
      },
    
      {
        path: '/crear-tienda/:id?',
        name: 'crear-tienda',
        component: NuevaTienda,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/crear-tienda/:id/paso-2',
        name: 'crear-tienda-paso-2',
        component: NuevaTiendaPaso2,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/crear-tienda/:id/paso-3',
        name: 'crear-tienda-paso-3',
        component: NuevaTiendaPaso3,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/crear-tienda/:id/dsc',
        name: 'crear-tienda-dsc',
        component: NuevaTiendaPasoDsc,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/crear-tienda/:id/ose',
        name: 'crear-tienda-ose',
        component: NuevaTiendaPasoOse,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/pagos/tienda/:id',
        name: 'pagos',
        component: Pagos,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/pagar/comprobante/:id',
        name: 'comprobante',
        component: Comprobante,
        meta: { headersistema: false, requiresAuth: true, }
      },
      {
        path: '/tienda/:id',
        name: 'tienda',
        component: InicioSistema,
        meta: { headersistema: true, requiresAuth: true, }
      },
        
    ],
    linkExactActiveClass: 'active',
      mode: 'history',
      scrollBehavior(){
          return {x:0, y:0}
      }
    });
    
    let isLoggedIn = store.getters.isLoggedIn()
      console.log(isLoggedIn)
    
    router.beforeEach((to, from, next) => {
      
      if (to.matched.some(record => record.meta.requiresAuth)) {
        
        // this route requires auth, check if logged in
        // if not, redirect to login page.
    
        if (!isLoggedIn) {
          next({
            path: '/ingresar',
            query: { redirect: to.fullPath }
          })
        } else {
          next()
        }
      } else {
        next() // make sure to always call next()!
      }
    })
    
    /**
     * Next, we will create a fresh Vue application instance and attach it to
     * the page. Then, you may begin adding components to this application
     * or customize the JavaScript scaffolding to fit your unique needs.
     */
    
    const app = new Vue({
      el: '#app',
      store: new Vuex.Store(store),
      components: {
          Loading,
        },
        router,
    });

게이터를 위한 Vue 설명서에서 게터에게 전화를 거는 방법은 다음과 같다.

store.getters.isLoggedIn

문서에는 현재와 유사한 방식으로 게터에게 전화를 거는 사례가 수록되어 있다.

함수를 반환하여 게이터에게 인수를 전달할 수도 있다.이것은 저장소의 배열을 쿼리할 때 특히 유용하다.

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

이와 같은 게이터를 가져와 보십시오.

<template>
    <div v-if="isLoggedIn">User Online</div>
    <div v-else>User Offline</div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
    name: "MyApp",
    computed: {
        ...mapGetter(["isLoggedIn"])
    }
};
</script>

참조URL: https://stackoverflow.com/questions/63270741/undefined-when-calling-state-in-getter-vuex

반응형