Vue,如何规范化复杂数据和分配唯一ID

时间:2018-12-08 23:36:27

标签: javascript vue.js

嘿,我一直在阅读有关规范复杂数据的文章。目前,我有一个对象,需要在单击按钮时生成新对象。我需要通过同样单击创建的组件中的唯一ID来访问对象。下面的过程图片。我不知道如何将新对象分配给父对象?并规范化我的数据,使其可能具有数百个唯一的预算行对象。任何帮助都会很棒,我了解论坛的帖子,但不知道如何将其应用于我的情况

Vue Forums Vue Forum Post 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.log(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')
    }
  }
}

On load of webpage, both label and other input will edit, inputbudget and amountbudgeted respectivly

On two clicks, two more child components are created with unique ids

1 个答案:

答案 0 :(得分:0)

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