我正在嘗試 Vue,但在將來自 Vuex 的資料與我的表單系結時遇到了問題。我創建了一個簡單的商店
export default {
state: {
form: {},
},
action: {
async getForm({ commit }, id) {
try {
const response = await axios.get(`url/${id}`);
commit('setForm', response.data);
} catch(e) {
console.error(e);
}
},
},
mutations: {
setForm(state, payload) {
state.form = payload;
},
},
getters: {
getFormFromStore = state => state.form,
},
}
我創建了一個簡單的組件
data() {
return {
form: {},
};
},
computed: {
...mapGetters('form', 'getFormFromStore'),
},
methods: {
...mapActions('form', 'getForm'),
},
watch: {
getFormFromStore: {
deep: true,
handler(newVal) {
this.form = Object.assign({}, newVal);
},
},
},
async mounted() {
await this.getForm();
},
<div>
<v-form>
<v-text-field v-model=form.name/>
<v-text-field v-model=form.lastName/>
<v-text-field v-model=form.age/>
<v-text-field v-model=form.address.street/>
<v-text-field v-model=form.address.house/>
<v-text-field v-model=form.children.girl/>
<v-text-field v-model=form.children.girl.name/>
</v-form>
</div>
但是當我嘗試更改表單時遇到了問題。我不知道如何解決它。我讀過一些文章,但它說我需要創建計算屬性,但是如果我有 100 個欄位的表單?
我的錯誤
錯誤 [vuex] 不要在變異處理程式之外改變 vuex 存盤狀態。
uj5u.com熱心網友回復:
Object.assign制作state.form. 雙向系結會v-model改變狀態。
觀察者應該做一個深拷貝。如果有多層嵌套,可以使用第三方工具進行深度克隆/合并。一種簡單且效率較低的方法是使用JSON內置創建深層副本:
this.form = JSON.parse(JSON.stringify(newVal));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370447.html
上一篇:Nuxt將GTM(noscript)添加到每個頁面/路由的body標簽中
下一篇:在IIS上部署VUE應用程式
