Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
coder Avatar asked Aug 29 '18 07:08

coder


Video Answer


1 Answers

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 }}
like image 198
Rodrigo Duarte Avatar answered Oct 07 '22 18:10

Rodrigo Duarte