vue.js - Vue 和 Vuex : Updating state based on changes to the view

标签 vue.js vuex

我正在尝试构建

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

单击保存按钮时,状态将根据用户添加到 View 的新数据进行更新。

目前,输入绑定(bind)到存储数据,因此我没有引用输入的“实时”值。当用户单击“保存”时,如何获取“实时”值?

组件模板

<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;
  }
}

潜在的解决方案

我想我也许可以创建商店的“克隆”,并将输入绑定(bind)到克隆的项目数据。然后,该对象将随着 View 的更改而更新,因此我可以获取这些“实时”值,并将数据从 View 提交到存储。这是一个好的解决方案吗?

最佳答案

如果您想在用户不必单击按钮的情况下进行更新,那么我建议 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>

关于vue.js - Vue 和 Vuex : Updating state based on changes to the view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757552/

相关文章:

javascript - 我应该如何正确调用NuxtServerInit?

javascript - vue.js中如何向组件发送数据?

javascript - 如何删除 Vue.js 中的元素?

javascript - 如何使用 javascript vuejs 有条件地导入内部 css?

vue.js - VuexFire 突变

javascript - 有多少业务逻辑属于 Vuex?

javascript - Vue将input[type=number]转换为字符串值

javascript - 如何将 Vue 的主应用渲染到 body 元素?

javascript - 为什么 Vue.js 模板无法与其脚本交互?

vue.js - 如何将 API 响应中的数据分配给状态?