2017-10-15 105 views
1

我試圖建立Vue公司和Vuex:更新基於改變狀態的視圖

呈現一種形式,其中默認的輸入值等於從存儲器中的數據的應用程序。

點擊保存按鈕後,將根據用戶添加到視圖中的新數據更新狀態。

當前輸入被綁定到商店數據,所以我沒有提及輸入的「實時」值。當用戶點擊保存時,我如何獲取「實時」值?

組件模板

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

可能的解決方案

我想我也許可以創造一個商店的 「克隆」,並綁定輸入到克隆它em數據。然後這個對象會隨着視圖的變化而更新,所以我可以抓住這些「實時」值,並將視圖中的數據提交給商店。這是一個好的解決方案嗎?

+0

看看文檔:https://vuex.vuejs.org/en/forms.html特別是第二款「雙向計算財產」。 – sandrooco

回答

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>