有人可以帮助我解决这个问题的生命周期吗?
我有2个vue组件1.有一个按钮(Header.vue)
和2.我想要隐藏/显示的侧边栏取决于值
标头看起来像这样<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>
侧边栏更大但修剪版本是这样的:
<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');
}
...
更新:添加了store.js
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;
}
},
我也尝试在模板v-bind中使用:class =&#34; {&#39; is-hidden-touch&#39; :sidebar.hideSidebarMobile}&#34;,但也没有运气,因为我可以看到值已更新但我无法添加/删除该类我哪里出错?
已更新...忘记上传商店
答案 0 :(得分:2)
侧边栏模板中的store.state.hideSidebarMobile
引用不起作用。 (除非你在侧边栏的Vue实例上设置store
属性等于Vuex商店,我假设你没有。)
如果您已正确注册Vuex模块:
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
...
});
然后您应该可以通过this.$store
引用侧边栏组件中的商店了。这也意味着无需将store
导入到需要引用它的每个文件中。
所以在你的模板中:
v-bind:class="{'is-hidden-touch' : $store.state.hideSidebarMobile}"