项目中遇到父组件传值 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>
参考网址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>
//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>