Home > Blockchain >  Passing a prop to data object in Vue3 Typscript
Passing a prop to data object in Vue3 Typscript

Time:11-24

I have a Vue component (a table) which receives an array of objects via props. Now I want to delete, add or edit some entries in this array but I cant do that as the prop is ready-only. So I thought upon receiving the property I just copy that thing into an object in the data-section of said component, which i should be able to edit but I havent found out how to do it.

Say items is my property and ditems is my data object

  data() {
    return { ditems: this.items };
  },

isnt working and neither is

  data() {
    let pitems = Object.assign({}, this.items);
    return { ditems };
  },

so I'm running out of ideas and I hope someone can help me Thanks in advance for your time

CodePudding user response:

When you try to edit the props value, you are right about duplicate the prop by either using Object.assign() or JSON.parse(JSON.stringify())(I recommend the JSON parse way btw).

However, the duplicate method is better put within watch instead of data(), given the prop data might be empty initially, and comes with data after an api request or something. So you'd better do this:

data() {
  return {
    ditems: {}
  }
}
watch: {
  items: {
    handler(val) {
      if (Object.keys(val).length) { // check whether items data is empty
        this.ditems = JSON.parse(JSON.stringify(val))
      }
    },
    deep: true
  }
}

And by the way, what you are using seems like Vue2, since Vue3 uses setup() instead of data().

  • Related