Vue 之温习 component 的世界 - slot

网页上难免有些内容,会需要差不多的架构,仅替换部分的内容,简单来说,我们前面讲到的元件拿来重複利用,只是我们要替换掉部分的内容,让元件可以达到最佳的利用化,这时候就要介绍的 slot 了,他是元件替换部分内容的角色

首先我们先来创建一个元件:

<div id="app">    <test-component></test-component></div><script type="text/x-template" id="test-component">  <nav aria-label="breadcrumb">    <ol class="breadcrumb">      <li class="breadcrumb-item"><slot name="test3">Home</slot></li>      <li class="breadcrumb-item"><a href="#">Library</a></li>      <li class="breadcrumb-item active" aria-current="page">Data</li>    </ol>  </nav></script><script>    Vue.component('test-component', {        template: '#test-component'    });</script>

直接在元件内打字是无效的:

如果我们直接在元件内,打上我们自己想要新增的内容,这是无效的,Vue 并不会去把它编译出来。

<div id="app">    <test-component>        <p>Lorem</p>    </test-component></div>

藉由 slot 新增单一内容:

如果我们的内容只有一个,直接在 x-template 的地方,新增 slot 标籤进去,并在元件内所需要的内容即可。

<div id="app">    <test-component>        <!-- 打上我们要新增的内容 -->        <p>Lorem</p>    </test-component></div><script type="text/x-template" id="test-component">  <nav aria-label="breadcrumb">    <ol class="breadcrumb">      <li class="breadcrumb-item"><a href="#">Home</a></li>      <li class="breadcrumb-item"><a href="#">Library</a></li>      <li class="breadcrumb-item active" aria-current="page">Data</li>      <!-- 这里新增 slot 标籤,把内容插进去 -->      <slot></slot>    </ol>  </nav></script>

具名的 slot 替换内容:

如果要替换多处元件的内容,这时候就要把替换的内容跟 slot 标籤对应上

<div id="app">    <test-component>        <!-- 打上我们要新增的内容,并赋予 slot 属性,值可以自定义,但需跟 x-template 的 name 属性相对应 -->        <li slot="newHome" class="breadcrumb-item"><a href="#">newHome</a></li>        <li slot="newLibray" class="breadcrumb-item"><a href="#">newLibray</a></li>    </test-component></div><script type="text/x-template" id="test-component">  <nav aria-label="breadcrumb">    <ol class="breadcrumb">      <!-- 在对应的位置上,改成 slot 标籤,并赋予 name 属性,值可以自定义,但需跟元件要替换的内容的 slot 属性的值一样-->      <slot name="newHome" class="breadcrumb-item"><a href="#">Home</a></slot>      <slot name="newLibray" class="breadcrumb-item"><a href="#">Library</a></slot>      <li class="breadcrumb-item active" aria-current="page">Data</li>    </ol>  </nav></script>

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章