Привет, я читал статьи о нормализации сложных данных. В настоящее время у меня есть объект, для которого требуется создание новых объектов при нажатии кнопки. Мне нужно получить доступ к объектам по уникальным идентификаторам в компоненте, который также создается одним щелчком мыши. Фотографии процесса ниже. Я не знаю, как назначать новые объекты моему родительскому объекту? а также нормализовать мои данные на наличие потенциально сотен уникальных объектов строки бюджета. Любая помощь была бы замечательной, я понимаю сообщения на форуме, но не знаю, как применить их в моей ситуации.
Форумы VueСообщение на форуме Vue 2
state: {
// Current state of the application lies here.
// budgetRows array at webpage load, base state
budgetRows: {}
},
getters: {
// Compute derived state based on the current state. More like computed property.
// Gets budgetRows array from state
budgetList: state => {
return state.budgetRows
},
// should get single array items from budgetRows based on component being accessed
budgetListItem: state => {
return state.budgetRows
}
},
mutations: {
// Mutate the current state
// Used to create a new row and push into budgetRows array (generate uniq id as well)
createRow (state) {
const uid = uniqId()
Object.assign(state.budgetRows, {[uid]: defaultRow})
// console.info(state.budgetRows)
},
Дочерний компонент:
<div v-for = "(budget, index) in budgetRowsList" :key = "index">
{{ index }}
<budgetItemRowContent></budgetItemRowContent>
<progress data-min = "0" data-max = "100" data-value = "20"></progress>
</div>
</div>
</div>
<footer class = "budgetGroupFooter">
<div class = "budgetGroupFooter-Content budgetGroupFooter-Content--Narrow">
<button class = "addBudgetItem" id = "addBudgetItem" v-on:click = "createNewContent()">
<svg xmlns = "http://www.w3.org/2000/svg" width = "8" height = "8" viewBox = "0 0 8 8">
<path fill = "#FD0EBF" d = "M3 0v3h-3v2h3v3h2v-3h3v-2h-3v-3h-2z"></path>
</svg>
Add Item
</button>
</div>
</footer>
<script>
import budgetItemRowContent from '../components/budgetItemRowContent.vue'
import { store } from '../store'
export default {
name: 'budgetGroup',
components: {
budgetItemRowContent,
store
},
data: () => {
return {
budgetItemHeading: 'Housing'
// creates array containing object for budget row information
}
},
computed: {
budgetRowsList () {
return this.$store.getters.budgetList
}
},
methods: {
createNewContent () {
this.$store.commit('createRow')
}
}
}
При двух щелчках мыши создаются еще два дочерних компонента с уникальными идентификаторами.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Vue.set - предпочтительный метод добавления новых свойств к существующему объекту, Object.assign - другой:
import Vue from 'vue'
// define an initial object state
const defaultRow = {
inputBudget: '',
amountBudgeted: 0,
remaining: 0
}
const state = {
budgetRows: {}
}
const mutations = {
createRow (state) {
const uid = uniqId()
// with Vue.set
Vue.set(state.budgetRows, uid, defaultRow)
// with Object.assign()
Object.assign(state.budgetRows, { [uid]: defaultRow })
}
}
Я обновил ответ, демонстрируя другой метод: Vue.set.
Спасибо, @DigitalDrifter. В итоге я сделал что-то очень похожее на это, и ваше выглядит чище, поэтому я реализовал этот стиль. Проблема, с которой я сейчас сталкиваюсь, заключается в том, что мое вычисляемое свойство не обновляется при создании новой строки. Обновлен код, чтобы отразить задачу.