Search code examples
vue.jscomputed-propertiesvue-props

When i want to change prop in the setter "avoid mutating prop error" shows


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?


Solution

  • 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.