@maestro07

Как использовать vuex во vue компоненте?

Пытаюсь реализовать авторизацию в проекте. Создал компонету start и реализовал запрос, и получаю ответ и делаю redirect.

Надо чтобы авторизации была глобальная для всего проекта, чтобы не могли пройти по ссылке, если не авторизовались.
Знаю что надо vuex.

1) Создал папку store
2) Создал папку module в store
3) Создал store.ts в store
import Vue from 'vue';
import Vuex, { StoreOptions } from 'vuex';
import { RootState } from './types';
import auth from '@/store/modules/auth';

Vue.use(Vuex);

const store: StoreOptions<RootState> = {
  modules: {
    auth
  }
};

export default new Vuex.Store<RootState>(store);


4) Создал auth.ts в папке modules
import axios from 'axios';


const state = {
  isAuthenticated: false
};

const getters = {
  isAuthenticated: state => state.isAuthenticated
};

const actions = {
  login(commit) {
    commit('loginRequest', false);
    axios.get('api/auth/me')
      .then(response => {
        console.log('response', response);
        commit('loginSucess', true);
        this.$router.push({
          name: 'Home',
        });
      })
      .catch(error => {
        console.log('error', error.response);
        commit('loginFailture', true);
        this.$router.push({
          name: 'Unwork',
          params: {
            message: error.response.data.message
          }
        });
      });
  }
};


const mutations = {
  loginRequest(state) {
    state.isAuthenticated = false;
  },

  loginSucess(state) {
    state.isAuthenticated = true;
  },

  loginFailture(state) {
    state.isAuthenticated = false;
  }
};

export default ({
  state,
  getters,
  actions,
  mutations
});


5) код в start.component.ts

import Component from 'vue-class-component';
import { Inject, Vue } from 'vue-property-decorator';
import StartService from './start.service';
import { Getter, Action } from 'vuex-class';

@Component
export default class Start extends Vue {
  @Inject('startService') public startService: () => StartService;
  @Getter('state') public tmp: any;
  created() {
    console.log('tmp', this.tmp);
    // this.startService()
    //   .auth()
    //   .then(response => {
    //     console.log('response', response);
    //     this.$router.push({
    //       name: 'Home',
    //     });
    //   })
    //   .catch(error => {
    //     console.log('error', error.response);
    //     this.$router.push({
    //       name: 'Unwork',
    //       params: {
    //         message: error.response.data.message
    //       }
    //     });
    //   });
  }
}


Не могу использовать vuex в компоненте. Подскажите в чем проблема?
  • Вопрос задан
  • 437 просмотров
Пригласить эксперта
Ответы на вопрос 1
@gribanov2la
Full stack web разработчик
Возможно, Вы не подключили vuex во vue инстанс.

Скорее всего проблема в декораторе @Getter('state') public tmp: any; . т.к. геттера state в сторе у вас нет. Попробуйте воспользоваться декоратором @State
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы