【问题标题】:Vue 3 pass data in <slot>Vue 3 在 <slot> 中传递数据
【发布时间】:2021-10-31 21:19:39
【问题描述】:

我想要达到的目标:
从 Post.vue 中的动态链接显示一张图片,它遵循 PostLayout.vue 的布局

在 PostLayout.vue 中,我有一个名为 postFeaturedImage 的 ,而在 slot 里面,有一个

,我想用图片作为它的背景。

我正在使用什么: Laravel、InertiaJS、Vue 3

我的代码是:

Post.vue:

<template>
    <PostLayout>
        <template #postfeaturedImage>
            <!-- Here I want to display the image -->
        </template>
    </PostLayout>
</template>

<script>
import PostLayout from '@/Layouts/PostLayout'

export default {
    data() {
        return {
            featured_image: ''
        }
    },
    components: {
        PostLayout,
    },
    props: {
        post: Object /* Passed the prop from Controller */
    },
    mounted () {
        this.featured_image = this.post.featured_image
    }
}
</script>

PostLayout.vue:

<template>
    <slot name="postfeaturedImage" :bgImage="bgImage">
        <div :style="`background-image:url(${bgImage}); height: 75vh;`"></div>
    </slot>
    
</template>

<script>
    export default {
        
    }
</script>


我已经删除了所有不相关的代码。我是 Vue 3 和 Inertia 的初学者,需要帮助!

【问题讨论】:

    标签: javascript vue.js vuejs3 inertiajs


    【解决方案1】:

    另一种方法是创建一个FeaturedImage 组件。此外,您可以直接从收到的道具中引用帖子图像。在这种情况下,不需要data 方法和mounted

    <template>
       <PostLayout>
          <template #postfeaturedImage>
             <FeaturedImage :src="post.featured_image" />
          </template>
       </PostLayout>
    </template>
    
    <script>
    import PostLayout from '@/Layouts/PostLayout'
    import FeaturedImage from '@/Layouts/FeaturedImage'
    
    export default {
       components: {
          PostLayout,
          FeaturedImage
       },
       props: {
          post: Object
       }
    }
    </script>
    

    【讨论】:

      【解决方案2】:

      在 PostLayout.vue 中添加一个 props

      <script>
      export default {
        props: {
          bgImage: { type: String },
        },
      };
      </script>
      

      并在 Post.vue 中为该道具赋值

      <template>
          <PostLayout :bgImage="featured_image"> </PostLayout>
      </template>
      

      如果您想要发布没有图片和不同布局的帖子,您应该这样做:

      <template>
          <PostLayout>
            <template #postfeaturedImage> post without background image</template>
          </PostLayout>
      </template>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-14
        • 2021-12-31
        • 2021-10-30
        • 2020-09-24
        • 2021-07-05
        • 2021-05-18
        • 2019-05-10
        相关资源
        最近更新 更多