首页 > 解决方案 > 处理 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 张卡片中使用这张卡片的相同描述。那么现在除了在每张卡片上写同样的东西之外,我还能做些什么聪明的事呢?如果在同一个视图文件中以及如果我需要在项目的不同视图文件中使用此部分怎么办?提前致谢。

标签: vue.jsnuxt.js

解决方案


将其放入组件中并制作imga 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>

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


推荐阅读