在nuxt js中处理重复部分的最佳方法是什么?

时间:2019-12-28 05:22:31

标签: vue.js nuxt.js

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

<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张以上的卡片中使用相同的卡片描述。那么,除了在每张卡上写相同的东西之外,我现在还能做什么呢?如果在同一视图文件中怎么办?如果需要在项目的其他视图文件中使用本节怎么办?预先感谢。

1 个答案:

答案 0 :(得分: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>

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

相关问题