将 Vuetify 导航抽屉 v 建模切换为 Vuex 变量

Tre*_*aul 2 javascript vue.js vuex vuetify.js

(我发现了一些类似的问题,但似乎没有一个能解决我的问题,但是如果我错过了什么,请参考。)

我正在使用 Vue、Vuex 和 Vuetify。根据“Google Keep”示例布局,我分解出了 NavDrawer 和 AppBar 组件。然而,我在使 NavDrawer 切换正常工作时遇到了一些麻烦。

在实现 Vuex 之前,我使用了 props 和 events,遍历了父组件。使用Vuex,我的代码如下:

main.js:

const store = new Vuex.Store({
  state: {
    drawerState: null
  },
  mutations: {
    toggleDrawerState(state) {
      state.drawerState = !state.drawerState
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

应用栏.vue:

<template>
  <v-app-bar app clipped-left class="primary">
    <v-app-bar-nav-icon @click="toggleDrawer()"/>
  </v-app-bar>
</template>

<script>
export default {
  name: 'AppBar',
  methods: {
    toggleDrawer: function() {
      this.$store.commit('toggleDrawerState')
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

导航抽屉.vue:

<template>
  <v-navigation-drawer v-model="drawerState" app clipped color="grey lighten-4">
    <!-- content -->
  </v-navigation-drawer>
</template>

<script>
export default {
  name: 'NavigationDrawer',
  computed: {
    drawerState: {
      get: function() { return this.$store.state.drawerState },
      set: () => null
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

NavDrawer 的计算属性set: () => null中的 是因为我首先将其设置为调用突变,这导致了切换的反馈循环。

现在,我的问题是,给定初始v-modelnull,Vuetify 会在桌面上打开抽屉并在移动设备上关闭。当 被drawerState = !drawerState调用时, 被null创建true,但这只是使抽屉在桌面上保持打开状态,这意味着必须再次单击该按钮才能关闭抽屉。在出现最初的双触发问题之后,它在桌面上运行良好。然而,在移动设备上,它总是需要两个触发器。(我说的是移动设备,但实际上我只是缩小了浏览器窗口的大小。)我认为这是因为在调整大小(或加载时)时,抽屉会自动隐藏,但无法更新 Vuex 存储布尔值,这意味着双触发器是必要的。

因此,我的问题是:实现 Vuetify 的 navdrawer 的标准或最佳实践方法是什么,以便从另一个组件切换它?我认为状态(无论是打开还是关闭)可能会直接存储,但没有“打开”或“关闭”事件可以访问它。(例如,这个问题没有答案。)它在示例页面上运行良好,但是如何将其调整为作为子组件工作?

谢谢!

Jam*_*now 6

使用 Vuex getter 并在计算的 getter 中引用它们,以及在计算的 setter 中检索新值并使用它在存储中提交突变是一个不错的选择。所以你的商店将变成:

const store = new Vuex.Store({
  state: {
    drawerState: false
  },
  mutations: {
    toggleDrawerState (state, data) {
      state.drawerState = data
    }
  },
  getters : {
    drawerState: (state) => state.drawerState
  }
})
Run Code Online (Sandbox Code Playgroud)

你的导航抽屉组件将变成:

<template>
  <v-navigation-drawer v-model="drawerState" app clipped color="grey lighten-4">
    <!-- content -->
  </v-navigation-drawer>
</template>

<script>
export default {
  name: 'NavigationDrawer',
  computed: {
    drawerState: {
      get () { return this.$store.getters.drawerState },
      set (v) { return this.$store.commit('toggleDrawerState', v) }
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

这是一个显示完整示例的 codepen: https: //codepen.io/JamieCurnow/pen/wvaZeRe