【问题标题】:What's the best way to handle repeated section's in nuxt js?处理 nuxt js 中重复部分的最佳方法是什么?
【发布时间】:2019-12-28 13:33:14
【问题描述】:

好吧,作为一个 nuxt js 学习者,我很好奇在视图文件中使用重复的 HTML 代码部分的最佳方法是什么。例如,这里有一个代码 sn-p :

<template>
  <div class="card flex-md-row mb-4 shadow-sm h-md-250">
      <div class="card-body d-flex flex-column align-items-start">
      <strong class="d-inline-block mb-2 text-primary">World</strong>
      <h6 class="mb-0">
          <a class="text-dark" href="#">40 Percent of People Can’t Afford Basics</a>
      </h6>
      <div class="mb-1 text-muted small">Nov 12</div>
      <p class="card-text mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p>
      <a class="btn btn-outline-primary btn-sm" role="button" href="http://www.jquery2dotnet.com/">Continue reading</a>
            </div>
            <img class="card-img-right flex-auto d-none d-lg-block" alt="Thumbnail [200x250]" src="//placeimg.com/250/250/arch" style="width: 200px; height: 250px;">
  </div>
<template>

想象一下,我只需要更改图像,就需要在另外 10 张卡片中使用此卡片的相同描述。那么现在除了在每张卡片上写同样的东西之外,我还能做些什么聪明的事呢?如果在同一个视图文件中以及如果我需要在项目的不同视图文件中使用此部分怎么办?提前致谢。

【问题讨论】:

  • 通过从外部传递 props 数据来填充此模板

标签: vue.js nuxt.js


【解决方案1】:

把它放在一个组件中,把img变成slot

<template>
    <div class="card flex-md-row mb-4 shadow-sm h-md-250">
        <div class="card-body d-flex flex-column align-items-start">
            <strong class="d-inline-block mb-2 text-primary">World</strong>
            <h6 class="mb-0">
                <a class="text-dark" href="#">40 Percent of People Can’t Afford Basics</a>
            </h6>
            <div class="mb-1 text-muted small">Nov 12</div>
                <p class="card-text mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p>
                    <a class="btn btn-outline-primary btn-sm" role="button" href="http://www.jquery2dotnet.com/">Continue reading</a>
            </div>
            <slot name="image">
                <img class="card-img-right flex-auto d-none d-lg-block" alt="Thumbnail [200x250]" src="//placeimg.com/250/250/arch" style="width: 200px; height: 250px;">
            </slot>
        </div>
    </div>
<template>

然后你可以使用该组件并将图像传递给image插槽:

<cool-component>
  <template slot="image">
    <img src="whatever"/>
  </template>
</cool-component>

或者您可以在组件中将该插槽留空,它将默认为定义的图像。

【讨论】:

  • 如果我将所有细节作为一个组件并更改所有卡片的图像怎么办?我实际上一直在寻找这种类型的解决方案。
  • @OsmanRafi 除非我有误解,否则这正是这里发生的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2013-03-03
相关资源
最近更新 更多