Answer the question
In order to leave comments, you need to log in
How to use vuex in vue component?
I'm trying to implement authorization in a project. I created the start component and implemented the request, and I get a response and do a redirect.
It is necessary that authorization be global for the entire project, so that they cannot follow the link if they are not authorized.
I know what vuex needs.
1) Created store folder
2) Created module folder in store
3) Created store.ts in 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);
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
});
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
// }
// });
// });
}
}
Answer the question
In order to leave comments, you need to log in
You may not have included vuex in your vue instance.
Most likely the problem is in the decorator @Getter('state') public tmp: any; . because you don't have a state getter in the store. Try using the @State decorator
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question