【问题标题】:How to change computed object in Vue?如何更改 Vue 中的计算对象?
【发布时间】:2018-05-07 06:00:41
【问题描述】:

我有简单的月份选择:

<select v-model="month" v-on:change="dateChanged('month', month)">
    <option v-for="(month, index) in months" :value="index">{{ month }}</option>
</select>

Vuex中存储的主要日期对象:

computed: {
    ...mapGetters(['date']), 
    month() {
        return this.date.format('M') - 1
    },

问题是,当我更改月份时,month 的值不会改变...在 select 中的视觉月份发生了变化,但值仍然与以前相同。

【问题讨论】:

  • 您可能想看看vuex.vuejs.org/en/forms.html 中的双向计算属性。 v-model 用于本地状态。你的月份状态是在 Vuex 中。 v-model="month" 将不起作用,除非您只想更改本地状态而不是 Vuex 状态

标签: javascript vue.js momentjs vuex


【解决方案1】:

这是因为computed 属性,顾名思义,只能在内部覆盖,它不是您可以写入的数据存储。如果您想从 VueX 存储中填充您的 month 并保持可写性,最好将其编写为以下组合:

  • 一个watcher 监视date,并在商店更新时更新内部month 数据
  • 一个简单地允许写入和读取month的内部数据

一个例子如下:

// Populate internal store with state data
data: function() {
    return {
        month: this.date.format('M') - 1
    }
},

// Map getter
computed: {
    ...mapGetters(['date'])
},

// Watch changes to mapped getter
watch: {
    date: function(val) {
        this.month = this.date.format('M') - 1
    }
}

当然,遵循 DRY 原则,您可能希望将逻辑抽象为一个单独的方法:

methods: {
    getMonth: function(month) {
        return month.format('M') - 1;
    }   
},
data: function() {
    return {
        month: this.getMonth(this.date)
    }
},
computed: {
    ...mapGetters(['date'])
},
watch: {
    date: function(val) {
        this.month = this.getMonth(val)
    }
}

【讨论】:

    猜你喜欢
    • 2023-01-04
    • 2019-12-05
    • 2020-04-20
    • 1970-01-01
    • 2018-04-25
    • 2021-08-14
    • 2020-10-19
    • 1970-01-01
    • 2014-07-05
    相关资源
    最近更新 更多