【问题标题】:Proper way to dynamically set many inputs values, getting data from Vuex store动态设置许多输入值的正确方法,从 Vuex 商店获取数据
【发布时间】:2017-11-10 22:17:43
【问题描述】:

我对 Vue 还是很陌生。我有很多输入的大表格。我希望将所有数据存储在 Vuex 存储中作为类的属性。

const store = new Vuex.Store({
    state: {
        cv: new CurriculumVitae()

我可以像这样轻松更新值:

<input @input="updateValue" name="name">
...
methods: {
    updateValue(e) {
        this.$store.commit('updateValue', {field: e.target.name, value: e.target.value});
    }
},
....
const store = new Vuex.Store({
    mutations: {
        updateValue (state, payload) {
            state.cv.data[payload.field] = payload.value;
        }
    }

我如何将一个充满数据的CurriculumVitae class 实例插入到存储中,并让所有输入自动预填充它的数据?我不想为每个输入都编写 v-model并单独填写。有没有更好、更动态的方法来实现这一目标?

编辑:我只想有一个更新对象的好方法。创建新的时 - 我不需要任何填充任何内容的输入。编辑时 - 将旧数据加载到输入中会很好。我喜欢它是动态的,而不是为每个输入编写模型并从存储中返回特定值。就像我在将更新保存到商店时所做的那样:这只是所有输入的一种方法。

Vue 是否提供了一种方法来做到这一点?

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    导出一个将返回数据的函数 // data.js

    export function CurriculumVitae() {
        return {data: {name: 'John Doe', gender: 'Male'} }
    }
    

    在存储文件中导入函数 // store.js

    import {CurriculumVitae} from 'data'

    实例化函数。 //store.js

    const store = new Vuex.Store({
    state: {
        cvs: CurriculumVitae() // here
    

    在组件文件中 // myComponent.vue

    computed: {
        cvs(){
            return store.state.cvs // here
        }
    }
    
    <input type="text" :value="cvs.data.name"> <!-- here -->
    

    看看这是否有效。

    【讨论】:

    • 我已编辑答案以在组件文件中添加用例。另外,请注意,我已经实例化了函数 int store 的状态,以便它实际返回对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2018-09-08
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多