Reputation: 620
can someone help me with the lifecycle of this?
I have 2 vue components 1. has a button (Header.vue)
and 2. is sidebar that I want to hide/show depends on value
header looks like this
<template>
<nav class="navbar" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a role="button" class="navbar-burger is-pulled-left" aria-label="menu" aria-expanded="false"
@click='getToggleSidebarMobile'>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
<a class="navbar-item " href="/">
<img :src="'/../images/logo.png'">
</a>
</div>
<div class="navbar-end is-pulled-right">
<div class="navbar-item">
</div>
</div>
</nav>
</template>
<script>
import {store} from '../store';
export default {
data() {
return {
hideSidebarMobile: store.state.hideSidebarMobile
}
},
methods: {
getToggleSidebarMobile(){
this.hideSidebarMobile = !this.hideSidebarMobile;
store.dispatch('getToggleSidebarMobile', this.hideSidebarMobile);
}
}
}
</script>
sidebar is bigger but trimmed version is this:
<template>
<aside class="menu " v-bind:class="{'is-hidden-touch' : store.state.hideSidebarMobile}" >
....
</aside>
</tamplate>
....
data() {
return {
sidebar: {
hideSidebarMobile: store.state.hideSidebarMobile
},
}
},
methods: {
getToggleSidebarMobile(){
store.dispatch('getToggleSidebarMobile');
}
...
update: store.js added
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
hideSidebarMobile: true
},
actions: {
getToggleSidebarMobile(context, payload){
console.log("action "+payload)
context.commit('getToggleSidebarMobile', payload)
}
},
mutations: {
getToggleSidebarMobile(state, data){
state.hideSidebarMobile = data;
console.log("Mutation "+data);
}
},
getters: {
getToggleSidebarMobile(state){
return state.hideSidebarMobile;
}
},
I also tried to use in template v-bind:class="{'is-hidden-touch' : sidebar.hideSidebarMobile}", but no luck in there as well, as I can see values are updated but I'm unable to add/remove that class where did I go wrong?
updated... forgot to upload store
Upvotes: 0
Views: 37
Reputation: 55644
The store.state.hideSidebarMobile
reference in the sidebar's template is not going to work. (Unless you've set a store
property on the sidebar's Vue instance equal to the Vuex store, which I'm assuming you haven't.)
If you've registered the Vuex module properly:
const store = new Vuex.Store({ ... }); // your store config
Vue.use(Vuex); // registering the plugin
new Vue({ // your root Vue instance
el: '#app',
store: store, // passing the `store` so components can reference this.$store
...
});
then you should be able to reference the store in your sidebar component via this.$store
. Which also means that there is no need to import store
into every file that needs to reference it.
So in your template:
v-bind:class="{'is-hidden-touch' : $store.state.hideSidebarMobile}"
Upvotes: 2