在Vue中,你可以通過作用域插槽(scoped slots)來傳遞數據給子組件。這同樣適用于具名插槽。首先,你需要在子組件中定義一個具名插槽,并通過v-slot
指令傳遞數據。例如:
子組件(ChildComponent.vue):
<template><div><slot name="myNamedSlot" :myData="myData"></slot></div>
</template><script>
export default {data() {return {myData: 'Hello from child component'};}
};
</script>
然后,在父組件中,你可以使用v-slot
指令來接收這個數據,并在插槽的模板中使用它:
父組件:
<template><ChildComponent><template v-slot:myNamedSlot="slotProps"><p>{{ slotProps.myData }}</p></template></ChildComponent>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent}
};
</script>
在這個例子中,slotProps
是一個對象,它包含了所有子組件傳遞給插槽的數據。你可以在插槽的模板中使用這些數據。注意,你需要使用v-slot:myNamedSlot
來指定你要接收的是哪個具名插槽的數據。