報錯:[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 bei


項目中遇到父組件傳值 activeIndex

 1 <Tabs :tabs="tabs" :activeIndex="activeIndex" ></Tabs>
 2 <script >
 3 export default{  4  updated(){  5           let currentRoute=this.$route.name;  6            var arr=Array.from(this.$store.state.app.tabs);  7            if(arr.indexOf(currentRoute)!=-1){  8 
 9              this.activeIndex=this.$store.state.app.activeIndex=arr.indexOf(currentRoute).toString(); 10  } 11 
12  } 13 } 14 </script>

子組件接收該值

 1 <template>  2 <el-tabs type="card" v-model="activeIndex" >  3 <el-tab-pane v-for="(item,index) in tabs" :label="item" :closable="index==0?false:true" :name="index.toString()" ></el-tab-pane>  4 </el-tabs>  5 </template>  6  7 <script>  8 export default{  9  data(){ 10 return { 11  tabs:[], 12  } 13  }, 14 15 props:['activeIndex'] 16 17  } 18 </script>

參考網址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的更改
 
 1 //v-model綁定更改
 2 <el-tabs type="card" v-model="currentIndex"  >   
 3 </el-tabs>
 4 <script>
 5   export default{  6  data(){  7             return {  8  tabs:[],  9               currentIndex:this.activeIndex //currentIndex接收父組件傳來的activeIndex值;
10  } 11  }, 12 
13       props:['activeIndex'] 14 
15  } 16 </script>
17 
18 作者:saintkl 19 鏈接:https://www.jianshu.com/p/392145843afe
20 來源:簡書 21 簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。

 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM