vue 动态组件的传值

时间:2023-03-09 09:05:35
vue 动态组件的传值

vue项目开发中会用到大量的父子组件传值,也会用到动态组件的传值,常规子组件获取父组件的传值时,第一次是获取不到的,这时候有两种解决方案

第一种:

父组件向子组件传的是一个json对象,ES6的方法Object.keys() 转化成数组,再判断数组的长度。如果传的是数组,直接判断长度就行

<!--父组件动态内容区域-->
<component :is="currentView" :clientDetails="clientDetails" v-if="Object.keys(clientDetails).length > 0"></component>

第二种:

第二种方法是子组件监听处理

<!--父组件动态内容区域-->
<component :is="currentView" :clientDetails="clientDetails"></component>
vue 动态组件的传值
<!--子组件监听-->
watch: {
clientDetails(newVal){
this.expandDetail = newVal;
console.log(this.expandDetail);
}
},
vue 动态组件的传值

注::is="currentView"是用来控制动态组件的,currentView的值改变会使用不同的子组件

贴一段项目中用到的代码

// 左侧菜单切换
handleChangeMenu (code) {
this.currentView = code
},
vue 动态组件的传值
components:{
expand: () => import('../groups/expand'),
certificates: () => import('../groups/certificates'),
contacts: () => import('../groups/contacts'),
addressview: () => import('../groups/addressview'),
credit: () => import('../groups/credit')
}
vue 动态组件的传值