報錯,props 不可重寫,需要複製給data重新定義

報錯:[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: "result" (found in component )

項目中遇到父組件傳值 activeIndex

<Tabs :tabs="tabs" :activeIndex="activeIndex" ></Tabs>
<script >
export default{
 updated(){
          let currentRoute=this.$route.name;
           var arr=Array.from(this.$store.state.app.tabs);
           if(arr.indexOf(currentRoute)!=-1){

             this.activeIndex=this.$store.state.app.activeIndex=arr.indexOf(currentRoute).toString();
           }

        }
}
</script>

子組件接收該值

<template>
      <el-tabs type="card" v-model="activeIndex"    >
        <el-tab-pane v-for="(item,index) in tabs" :label="item"  :closable="index==0?false:true" :name="index.toString()"  ></el-tab-pane>
      </el-tabs>
</template>

<script>
  export default{
      data(){
            return {
              tabs:[],
          }
        },

      props:['activeIndex']

    }
</script>

6ebadbe553e2f174006b.jpg

參考網址https://juejin.im/entry/5843abb1a22b9d007a97854c
由於父組件updated()方法中更改了this.activeIndex值,update方法除了父組件觸發這個方法,子組件也會觸發,即子組件會更改activeIndex的值,但是由於父子組件的傳遞機制,會造成報錯Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders....
因此在子組件使用該值時需要經過新變量(currentIndex)重新傳遞,這樣當這個值變更時,不會造activeIndex的更改

//v-model綁定更改
<el-tabs type="card" v-model="currentIndex"  >   
</el-tabs>
<script>
  export default{
      data(){
            return {
              tabs:[],
              currentIndex:this.activeIndex //currentIndex接收父組件傳來的activeIndex值;
          }
        },

      props:['activeIndex']

    }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章