Search code examples
javascriptvuejs2vue-componentbootstrap-vue

Vue component - how to avoid mutating a prop (Laravel component)


I get the following warning with my Vue component for Laravel:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever
the parent component re-renders. Instead, use a data or computed property based on the
prop's value. Prop being mutated: "benutzers"

found in

---> <BootstrapVueBTable1> at resources/js/components/b-table1.vue
       <Root>

I tried some variations of renaming, but I am not experienced.

<template>
  <div> <b-table striped hover :items="benutzers" > </b-table> 
  </div>
</template>

<script>
  export default {
    mounted() {
      this.loadData();
    },
    methods: {
      loadData:function() {
        axios.get('/api/benutzers').then(res => {
          if(res.status == 200) {
            this.benutzers = res.data;
          }
        }).catch(err => {
           console.log(err)
        });
      }
    },
    props: ['benutzers'],
  }
</script>

Solution

  • in some case you're still overwriting your props if you use

    <div v-for="benutzer in  parentbenutzers">
    

    so you need to change your v-for to this

    <div v-for="benutzer in  benutzers">
    
          props: ['parentBenutzers'],
    data() {
      return {
        benutzers: this.parentBenutzers,
      }
    },
    mounted(){
        this.loadData();
    },
    methods:{
        loadData:function(){
            axios.get('/api/benutzers').then(res=>{
              if(res.status==200){
                 this.benutzers=res.data;
              }
            }).catch(err=>{
               console.log(err)
            });
        }
    },