0

After I pass an array as a prop and trying to change prop in the setter (in computed) It shows me the "avoid mutating prop" error. and here's my code:

export default {
    props: {
        links: {
            type: Array,
            default: () => {
                return [];
            },
            required: true
        },
    },
    data() {
        return {
          data: {}
        };
    },
    computed: {
        links_data: {
            get() {
                return this.links
            },
            set(value) {
                this.$emit('update:links', {...this.links = value})
            }
        }
    },
    methods: {
        // Add new link
        addNewLink() {
          axios.post(api, this.data)
              .then(res => { this.links_data = res.data.links })
              .catch(error => {console.log(error)})
        },
        // Post delete
        deleteLink() {
            axios.delete(api)
            .then(res => { this.links_data = res.data.links })
            .catch(error => {console.log(error)})
        },
    }
};

any one knows why I get this error?

Niaz Estefaie
  • 567
  • 6
  • 21
  • Does this answer your question? [Vue 2 - Mutating props vue-warn](https://stackoverflow.com/questions/39868963/vue-2-mutating-props-vue-warn) – Anurag Srivastava Feb 13 '21 at 10:09
  • @AnuragSrivastava I tried this answer but I have to render a list with v-for. When the page initialized it does not show the list which passed to the props. – Niaz Estefaie Feb 13 '21 at 10:31

1 Answers1

2

you made wrong in setter,

 this.$emit('update:links', {...this.links = value})
  1. you have used this.links in left hand side to assign value, i mean you are directly trying to assign value into this.links so it is the cause of mutation error.

  2. you are trying to pass object into this.links instead of array though links props type is Array.

so try to resolve the above 2 issues, then i think it will work fine.

just replace the setter $emit like below,

 this.$emit('update:links', [...value])

or

this.$emit('update:links', value)

hope it will solve your issue.

Mahamudul Hasan
  • 2,745
  • 2
  • 17
  • 26
  • already updated my post, so change the $emit as like as given in post – Mahamudul Hasan Feb 13 '21 at 10:39
  • Thanks to you the error disappeared. Now the problem is when I add or delete an item in the array, my changes don't update and show in v-for. – Niaz Estefaie Feb 13 '21 at 10:45
  • 1
    may be you did not use .sync whenever you used links props in tag. as you know prop is unidirectional so parent to child. but you are trying child to parent. so you have to add .sync in your tag where you have used :links. so now you have to use :links.sync. – Mahamudul Hasan Feb 13 '21 at 10:46