报错:[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