在 Vuetify 中管理覆盖已关闭组件的状态 [英] Managing State for Overlay Dismissed Components in Vuetify
问题描述
我第一次构建了一个 vuetify/nuxt
前端,并且我已经将我的 v-navigation-drawer
组件移出了 default.vue
布局,并放入它自己的组件中,以便它可以在多个布局中重用.
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.
这个抽屉的激活器仍然保留在 default.vue
组件中,所以我在 vuex 中添加了一个 sidebar
状态:
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,
})
侧边栏的 mutator 如下所示:
The mutator for the sidebar looks like so:
export const mutations = {
toggleSidebar(state) {
state.sidebar = !state.sidebar;
}
}
这在打开抽屉时非常有效,但是因为通过单击覆盖层或单击侧边栏(如果您已关闭覆盖层)关闭了抽屉,vuex 会引发一个巨大的错误:
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:
如何通过 vuex 使其正常工作?
How can I make this work correctly through vuex?
推荐答案
不要将抽屉的模型直接绑定到 $store.state.sidebar
,而是在抽屉组件中使用计算的 setter.请注意,您必须从抽屉本身传入新值,不要只是切换存储中已有的值.
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
另一种选择是分别绑定 prop 和 event
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
这篇关于在 Vuetify 中管理覆盖已关闭组件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!