Managing State for Overlay Dismissed Components in Vuetify

自作多情 提交于 2020-01-13 03:39:14

问题


I'm building out a vuetify/nuxt frontend for the first time, and I've moved my v-navigation-drawer component out of the default.vue layout, and into it's own component, so that it can be reused in multiple layouts.

The activator for this drawer still remains in the default.vue component, so I added a sidebar state to vuex:

export const state = () => ({
    baseurl: 'http://example.com/api/',
    sidebar: false,
    authenticated: false,
    token: null,
    user: null,
})

The mutator for the sidebar looks like so:

export const mutations = {
    toggleSidebar(state) {
        state.sidebar = !state.sidebar;
    }
}

This works perfectly when opening the drawer, but because the drawer is dismissed via clicking the overlay, or clicking off of sidebar (if you've turned the overlay off) vuex throws a huge error:

How can I make this work correctly through vuex?


回答1:


Instead of binding the drawer's model directly to $store.state.sidebar, use a computed setter in the drawer component. Note that you must pass in the new value from the drawer itself, don't just toggle whatever's already in the store.

<template>
  <v-navigation-drawer v-model="drawer" ...>
</template>

<script>
  export default {
    computed: {
      drawer: {
        get () {
          return this.$store.state.sidebar
        },
        set (val) {
          this.$store.commit('sidebar', val)
        }
      }
    }
  }
</script>
// vuex mutation
sidebar (state, val) {
  state.sidebar = val
}

https://vuejs.org/v2/guide/computed.html#Computed-Setter
https://vuex.vuejs.org/en/forms.html

Another option is to bind the prop and event separately

<template>
  <v-navigation-drawer :value="$store.state.sidebar" @input="$store.commit('sidebar', $event)" ...>
</template>

https://vuejs.org/v2/guide/components.html#Using-v-model-on-Components



来源:https://stackoverflow.com/questions/47442621/managing-state-for-overlay-dismissed-components-in-vuetify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!