IT이야기

Vue/Vuex 서브스크라이버가 기동하지 않는 이유는 무엇입니까?

cyworld 2022. 6. 28. 23:20
반응형

Vue/Vuex 서브스크라이버가 기동하지 않는 이유는 무엇입니까?

사용자 인증을 localStorage에 저장하도록 Vuex 서브스크라이브 기능을 설정했는데 서브스크라이버가 부팅되지 않는 이유를 아무리 생각해도 알 수 없습니다.나는 심지어 그것을 얻을 수 없다.console.log()그것으로부터.여기 제 프로젝트의 관련 내용이 있습니다.

main.discloss.main.discloss.

import Vue from 'vue';
import Buefy from 'buefy';
import axios from 'axios';
import router from '@/router';
import store from '@/store';
import App from './App.vue';
import 'buefy/dist/buefy.css';
import '@/store/subscriber';

Vue.config.productionTip = false;

Vue.use(Buefy);

Vue.prototype.$http = axios;
const token = localStorage.getItem('x-auth-token');
if (token) Vue.prototype.$http.defaults.headers.common['x-auth-token'] = token;
Vue.prototype.$http.defaults.baseURL = 'http://localhost:5000/v1/';

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

store/index.displaces

import Vue from 'vue';
import Vuex from 'vuex';
import auth from './auth';
import transactions from './transactions';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    auth,
    transactions,
  },
});

store/subscriber.displacer.displaces

import Vue from 'vue';
import store from '@/store';

store.subscribe = (mutation) => {
  console.log(mutation);
  console.log("WHY AREN'T YOU WORKING!!!???");

  switch (mutation.type) {
    case 'auth/SET_TOKEN':
      if (mutation.payload) {
        Vue.prototype.$http.defaults.headers.common['x-auth-token'] = mutation.payload;
        localStorage.setItem('x-auth-token', mutation.payload);
      } else {
        Vue.prototype.$http.defaults.headers.common['x-auth-token'] = '';
        localStorage.removeItem('x-auth-token');
      }
      break;
    case 'auth/SET_USER':
      if (mutation.payload) {
        Vue.prototype.$http.defaults.headers.common.user = JSON.stringify(mutation.payload);
        localStorage.setItem('user', JSON.stringify(mutation.payload));
      } else {
        Vue.prototype.$http.defaults.headers.common.user = '';
        localStorage.removeItem('user');
      }
      break;
    default:
      Vue.prototype.$http.defaults.headers.common['x-auth-token'] = '';
      Vue.prototype.$http.defaults.headers.common.user = '';
  }
};

스토어/auth.module

import axios from 'axios';

export default {
  namespaced: true,
  state: {
    token: localStorage.getItem('x-auth-token') || '',
    user: {},
  },
  getters: {
    authenticated(state) {
      return state.token && state.user;
    },
    user(state) {
      return state.user;
    },
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
    },
    SET_USER(state, data) {
      state.user = data;
    },
  },
  actions: {
    async signIn({ commit, dispatch }, credentials) {
      try {
        const { data } = await axios.post('users/login', credentials);
        const { token, user } = data;
        if (token) {
          commit('SET_TOKEN', token);
        }
        commit('SET_USER', user);
        return data;
      } catch (err) {
        dispatch('signOut');
        return err.response;
      }
    },
    async registerUser({ commit, dispatch }, credentials) {
      try {
        const { data } = await axios.post('users/register', credentials);
        const { token, user } = data;
        if (token) {
          commit('SET_TOKEN', token);
        }
        commit('SET_USER', user);

        return data;
      } catch (err) {
        dispatch('signOut');
        return err.response;
      }
    },
    signOut({ commit }) {
      commit('SET_TOKEN', '');
      commit('SET_USER', {});
    },
  },
};

뷰/로그인표시하다

<template>
  <div>
    <h1 class="title has-text-centered is-size-1 mt-6">Log In</h1>
    <div class="box column is-half is-offset-one-quarter mt-6 px-6">
      <form @submit.prevent="handleSubmit" action="GET" class="my-5">
        <b-field label="Username" for="username" :type="usernameValidation">
          <b-input v-model="user.username" id="username" name="username" placeholder="Username"></b-input>
        </b-field>
        <b-field
          label="Password"
          for="password"
          :type="passwordValidation"
          :message="passwordMessage"
        >
          <b-input
            v-model="user.password"
            type="password"
            id="password"
            name="password"
            placeholder="Password"
            password-reveal
          ></b-input>
        </b-field>
        <div class="buttons is-centered">
          <b-button native-type="submit" class="is-success mt-5 mb-4 has-text-weight-bold">Log In</b-button>
        </div>
        <div class="level">
          <div class="level-left">
            <router-link class="level-item" to="/signup">Sign Up</router-link>
          </div>
          <div class="level-right">
            <router-link class="level-item" to="/forgotpassword">Forgot Password</router-link>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex';

export default {
  name: 'LogIn',
  data: () => ({
    user: {
      username: '',
      password: '',
    },
    usernameValidation: '',
    passwordValidation: '',
    passwordMessage: '',
  }),
  methods: {
    ...mapActions({
      signIn: 'auth/signIn',
    }),
    async handleSubmit() {
      const { data } = await this.signIn(this.user);
      if (data) {
        this.usernameValidation = 'is-danger';
        this.passwordValidation = 'is-danger';
        this.passwordMessage = data.message;
      } else {
        this.$router.push('/');
      }
    },
  },
};
</script>

너 완전 자책할 거야.

두 가지 문제

  1. 당신은 그것을 포함하지 않았다.subscribe.js서브스크라이버가 가입되지 않도록 하기 위해서입니다.그 후, 이것을 Import 하고 있습니다.main.js그 문제가 해결되는 거죠
  2. store.subscribe() 는, 유저 함수를 제공하지만, 새로운 함수를 할당하는 것으로, 콜 하는 함수입니다.대신 이것을 사용해 보세요.
store.subscribe((mutation) => {
  console.log(mutation);
  console.log("OMG YOU'RE WORKING!!!");

  // etc
})

goofy-architecture-pknzm 편집

언급URL : https://stackoverflow.com/questions/63696555/why-is-my-vue-vuex-subscriber-not-firing

반응형