【问题标题】:Nuxtjs: How to call component inside another component?Nuxtjs:如何在另一个组件中调用组件?
【发布时间】:2021-05-17 00:06:34
【问题描述】:

我理解范式“页面组件”,但是如果我有一个呈现组件的页面,我如何在该组件中调用另一个组件?目前 nuxtjs 不允许我这样做。我不能坚持标准的“页面组件”方案,因为我正在构建调用购物车项目的购物车。

说如果页面调用的购物车组件是这样的,它会如何调用里面的cart-item组件?

<!---- cart component called from index.vue --->

    <template>
        <div>
            <Cart-item></Cart-item> < ---------- This doesn't work.
        </div>
    </template>
    
    <script>
    export default {
        props: ['items']
    }
    </script>

【问题讨论】:

    标签: javascript vue.js nuxt.js


    【解决方案1】:

    我以标准方式管理它:

    <template>
            <div>
                <CartItem></CartItem>
            </div>
        </template>
        
        <script>
        import CartItem from  '../components/Cart-item'
        export default {
            props: ['items']
        }
        </script>
    

    由于 nuxtjs 自动注册所有组件,想知道是否有更优雅的方式。

    【讨论】:

      【解决方案2】:

      编辑:正如所承诺的,这里有一个示例,说明如何通过slots 将一些内容从另一个组件传递到另一个组件。这完全适用于任何 Nuxt 页面。

      NestedContent.vue

      <template>
        <div>
          <p>Here is the NestedContent component and below is a slot passed to ParentWithSlots' component</p>
          <hr />
          <parent-with-slots>
            <!-- <template #default> // this one can be omit since we do use the default slot here -->
            <p>This content is inserted into the component ParentWithSlots</p>
            <!-- </template> -->
          </parent-with-slots>
        </div>
      </template>
      

      ParentWithSlots.vue

      <template>
        <div>
          <p>xxxxxxxxxxx ParentWithSlots' content before slot xxxxxxxxxxx</p>
          <slot>Default content in case none is provided</slot>
          <p>xxxxxxxxxxx ParentWithSlots' content after slot xxxxxxxxxxx</p>
        </div>
      </template>
      

      这是它的外观

      PS:你也可以试试layouts,它对你的一些组件的整体定位很有用。


      如果您的组件位于components 目录中,您可以在nuxt.config.js 中设置components: true,并且几乎可以在任何地方使用&lt;cart-item&gt;&lt;/cart-item&gt; 语法访问它,无需任何额外步骤。

      更多细节在这里:https://nuxtjs.org/blog/improve-your-developer-experience-with-nuxt-components/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 2014-12-27
        • 2019-02-03
        • 1970-01-01
        • 2017-05-19
        • 1970-01-01
        • 2019-02-06
        相关资源
        最近更新 更多