【问题标题】:Checkbox state does not change on click单击时复选框状态不会更改
【发布时间】:2018-09-21 13:22:58
【问题描述】:

在我的 Model.vue 组件中(在 Nuxt.js 和 Vuetifyjs 应用程序中)我有这段代码:

<v-checkbox v-model="selected"></v-model>

在这个组件的脚本部分,我有:

computed: {
    selected: {
        get() {
            return this.$store.state.selected
        },
        set(value) {
            this.$store.commit('UPDATE_SELECTED', value)
        }
    },
},

在商店里,我有这个:

mutations: {
    UPDATE_SELECTED: (state, value) => {
       state.selected.push(value)
    }
}

并且该商店的状态包含选择的条目如下:

state: {
   selected: []
}

AFAIK,我遵守了documentation,但是当我点击v-checkbox 组件时,它没有选中/取消选中。怎么了?

【问题讨论】:

  • 从这个关于mutation 的文档部分我希望你的state.selected 是真或假而不是数组

标签: javascript vue.js vuetify.js nuxt.js


【解决方案1】:

出现问题是因为您正在使用一个数组来对名为 selected 的布尔状态属性进行建模。 因此,根据您的代码,在突变方面,在每个突变中,您将在名为 selected 的数组的最新位置推送一个新的布尔值。

此外,在获取端,计算属性的get() 函数将整个数组作为要显示的属性返回,从而导致客户端未选中复选框。

因此,假设您需要处理多个复选框,为了使当前的复选框正常工作,您可以编写如下:

Vuex 商店

let store = new Vuex.Store({
  state: {
   selected: []
  },
  mutations: {
    UPDATE_SELECTED: (state, value) => {
       //mutating the 0th array position of the selected property
       state.selected[0] = value
    }
  }
})

计算属性

computed: {
    selected: {
        get() {
       //getting the 0-index element of the array, assuming this checkbox is the 0th
            return this.$store.state.selected[0]
        },
        set(value) {
            this.$store.commit('UPDATE_SELECTED', value)
        }
    }
  }

在这里您可以找到working fiddle
或者,如果您只需要处理应用程序状态中的单个复选框,则将 state.selected 属性建模为布尔值就足够了。我的意思是,如下修改你的 Vuex 状态就足够了:

state: {
   selected: true //or false if you expect unchecked checkbox as default
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 2023-03-31
    相关资源
    最近更新 更多