coder
coder

Reputation: 642

How to access store values to components in vue js

This is my store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        isLoggedIn: !!localStorage.getItem('token'),
        isLog : !!localStorage.getItem('situation')
    },
    mutations: {
        loginUser (state) {
            state.isLoggedIn = true
            state.isLog = true
        },
        logoutUser (state) {
            state.isLoggedIn = false
            state.isLog = false
        },
    }
})

but when I call {{state.isLoggedIn}} in the display.vue, I am not getting the values.

In display.vue, I use

<script>
import axios from "axios";
import store from '../store';

export default {
  name: "BookList",
  data() {
    return {
      students: [],
      errors: [],
      state: this.state.isLoggedIn,

    };
  },
})
</script>

<template>
{{this.state}}
</template>

But I am getting errors when i done this way. Please can anyone please help what is the problem.

Upvotes: 7

Views: 36151

Answers (1)

Rodrigo Duarte
Rodrigo Duarte

Reputation: 331

You don't need to import your store into your component. Instead, you should access it using this.$store.

For accessing the store state, the better (and recommended) way is to map the state within your component.

In your example it should be something like:

import { mapState } from 'vuex'

export default {
    ...
    computed: {
        ...mapState({
            isLoggedIn: 'isLoggedIn'
        })
     }
}

In your template, this is not needed. Just call the property by its name:

{{ isLoggedIn }}

Upvotes: 16

Related Questions