【问题标题】:Vue and Vuex: Updating state based on changes to the viewVue 和 Vuex:根据视图的变化更新状态
【发布时间】:2018-03-27 05:18:43
【问题描述】:

我正在尝试构建

呈现表单的应用程序,其中默认输入值等于存储中的数据。

当点击保存按钮时,状态会根据用户添加到视图中的新数据进行更新。

当前输入绑定到存储数据,因此我没有参考输入的“实时”值。当用户点击保存时,如何获取“实时”值?

组件模板

<input type="text" class="form-control" :value="item.name">
<input type="text" class="form-control" :value="item.price">
<button class="btn btn-primary" v-on:click="updateItem(item)">Save</button>

组件

data: function() {
  return {}
},
methods: {
  updateItem(item) {
    this.$store.commit('updateItem', item);
  },
},
computed: {
  items() {
    return this.$store.getters.getItem;
  }
}

可能的解决方案

我想我或许可以创建商店的“克隆”,并将输入绑定到克隆的商品数据。然后这个对象将随着视图的变化而更新,因此我可以获取那些“实时”值,并将视图中的数据提交到存储中。这是一个好的解决方案吗?

【问题讨论】:

标签: vue.js vuex


【解决方案1】:

如果您想在用户无需单击按钮的情况下进行更新,那么我建议您使用one of the methods explained in the docs

但既然您想在他们点击按钮时这样做,请尝试以下操作:

<template>
    <form>
        <input type="text" class="form-control" v-model="item.name">
        <input type="text" class="form-control" v-model="item.price">

        <button class="btn btn-primary" @click.prevent="updateItem">Save</button>
    </form>
</template>

<script>
export default {
    data() {
        return {
            item: {
                name: null,
                price: null,
            }
        }
    },

    mounted() {
        // Set the default value of this.item based on what's in the store
        this.item = this.$store.getters.getItem
    },

    methods: {
        updateItem() {
            this.$store.commit('updateItem', this.item);
        }
    }
}
</script>

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 2022-01-22
    • 2020-07-08
    • 2019-10-05
    相关资源
    最近更新 更多