[Vuejs]-Avoid props mutation in vueJS

2👍

It’s an anti-pattern to modify prop directly in Vue

Instead, you can an emit an event from the child & modify the data in the parent which is being passed as the prop to the child as below:

parent.vue

<template>
  <child 
   MyProp="myData"
   @on-click-btn="handleClick" // [2] listen to the event & attach an handler to it
  />
</template>

export default {
 data () {
  return {
   myData: false
  }
 },
 // [3] event handler gets called when event is triggered ie. at user's click
 handleClick (currentValue) {
  // [4] modify the data, that is being passed as prop to the child, so that child recieves the updated data
  this.myData = !currentValue
 }
}

child.vue

<template>
  <button @click="handleClick">click me, I am {{ MyProp }}</button>
</template>

export default {
 props: ['MyProp'],
 method: {
  handleClick () {
   // [1] emit an event on user's click & pass the current prop value to it
   this.$emit('on-click-btn', this.MyProp)
  }
 }
}

demo

2👍

you can use the sync modifier:

Vue.component('child', {
  template: '#child',
  props: {
    val: {
      type: String, required: true
    }
  },
  methods: {
    handleInput(event) {
      this.$emit('update:val', event.target.value)
    }
  }
})

new Vue({
  el: '#app',
  data(){
    return {
      value: ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<script type="text/x-template" id="child">
  <input @input="handleInput">
</script>

<div id="app">
  <child :val.sync="value"></child>
  <div>{{ value }}</div>
</div>

Leave a comment