項目中遇到父組件傳值 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的更改
由於父組件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 簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。