多组件嵌套传值
现在用组件A 、组件B、组件C三个组件
一、组件嵌套
1.组件A(相当于父组件),在组件A调用组件B
<template> <div> <componentb></componentb> </div> </template> <script> import Componentb from '../components/componentb.vue' // 引用组件 export default { name: "ComponentA", //组件名称 components:{ Componentb }, // 定义组 provide: { valuea: "provide" } // 设置传值给组件B } </script>
2.组件B(相当于子组件),在组件B中调用组件C
<template> <div> <componentc></componentc> </div> </template> <script> import Componentc from '../components/compoentc.vue' // 引用组件 export default { name: "ComponentB", //组件名称
components:{ Componentc }, // 定义组
reject: ['value'], //获取父组件传递的值
provide: { valueb: "provide" } // 设置传值给组件C
data(){
return: {
providevalue:this.valuea
}
}
}
</script>
3.组件C(相当于孙组件)在组件c中获取值
<template> <div>
{{valueb}} </div> </template> <script> export default { name: "ComponentC", //组件名称
reject:["valueb"], // 获取传值 } </script>
二、多层插槽嵌套组件同样适用
组件A
<template>
<div>
<componentb>
<componentc/>
</componentb> </div> </template> <script> import Componentb from '../components/componentb.vue'
import Componentc from '../components/componentc.vue'
// ↑引用组件 export default { name: "ComponentA", //组件名称 components:{ Componentb,Compoentc }, // 定义组 provide: { valuea: "provide" } // 设置传值 } </script>
组件B
<template> <div> <slot/> </div> </template> <script> export default { name: "ComponentB", //组件名称 components:{ Componentc }, // 定义组 reject: ['value'], //获取父组件传递的值 provide: { valueb: this.providevalue }, // 设置传值给组件C data(){ return: { providevalue:this.valuea } } } </script>
组件C
<template> <div> {{providevalue}} </div> </template> <script> export default { name: "ComponentC", //组件名称 reject:["providevalue"], // 获取传值 } </script>
标签:provide,export,components,reject,组件,传值 From: https://www.cnblogs.com/suka/p/17318377.html