Vue3中如何向slot传递数据实现PostLayout动态背景图渲染(Laravel+InertiaJS)
问题解决步骤
你当前的需求是将Post.vue中拿到的动态图片地址传递给PostLayout的指定插槽,作为内部div的背景图,核心问题是PostLayout未声明接收图片参数、父组件没有完成参数传递,按以下步骤修改即可:
方案一:通过组件props传递(最简单,适合入门使用)
这种方案你不需要自定义插槽内容,直接用PostLayout自带的默认插槽渲染结构即可:
1. 修改PostLayout.vue
声明接收bgImage属性,代码如下:
<template> <slot name="postfeaturedImage" :bgImage="bgImage"> <div :style="`background-image:url(${bgImage}); height: 75vh;`"></div> </slot> </template> <script> export default { // 新增props声明,接收父组件传过来的背景图地址 props: { bgImage: { type: String, default: '' } } } </script>
2. 修改Post.vue
直接给PostLayout绑定bgImage属性,不需要额外定义data存储图片地址,也不需要写插槽自定义内容,代码如下:
<template> <!-- 给布局组件绑定背景图属性即可 --> <PostLayout :bgImage="post.featured_image"> <!-- 其他插槽内容 --> </PostLayout> </template> <script> import PostLayout from '@/Layouts/PostLayout' export default { components: { PostLayout, }, props: { post: Object /* 从控制器传递过来的参数 */ } // 不需要额外的mounted赋值逻辑,直接用props的post即可 } </script>
方案二:自定义插槽内容(如果你需要修改插槽内的div结构)
如果你要自己在Post.vue里写插槽内的div样式,不需要用Layout的默认结构,按以下修改Post.vue即可,不需要改动PostLayout代码:
<template> <PostLayout> <template #postfeaturedImage> <!-- 直接在父组件自定义的插槽内容里绑定背景图 --> <div :style="`background-image:url(${post.featured_image}); height: 75vh;`"></div> </template> </PostLayout> </template> <script> import PostLayout from '@/Layouts/PostLayout' export default { components: { PostLayout, }, props: { post: Object /* 从控制器传递过来的参数 */ } } </script>
内容的提问来源于stack exchange,提问作者Fariaz Khan
相关产品推荐
相关产品推荐

