Fenghe's Blog

Apply Vuex Store and v-if to a Vue CLI Project

There are quite many tutorials about vuex store out there, but most of them are too opaque for a novice to learn. This tutorial will teach you how to use Vuex Store in a project perspective instead of a single file demo.

In main.js

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    loggedin: false
  },
  mutations: {
    toggle(state) {
      // toggle the state
      state.loggedin = !state.loggedin;
    }
  },
  getters: {
    loggedin() {
      return state.loggedin;
    }
  }
})

new Vue({
  el: "#app",
  render: h => h(App),
  store,
  router
});

In .vue file,

<template>
    <side-bar v-if="loggedin" title="">
      ...
    </side-bar>
</template>

<script>
import TopNavbar from "./TopNavbar.vue";
import ContentFooter from "./ContentFooter.vue";
import DashboardContent from "./Content.vue";

export default {
  components: {
    TopNavbar,
    DashboardContent,
    ContentFooter
  },
  computed: {
    loggedin() {
      return this.$store.state.loggedin;
    }
  }
  
};
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *