Vue.js 组件中如何截取 Slot 内容并展示
<template>
<div>
<h1>{{ title }}</h1>
<div class='content'>
<slot name='main' slot-scope='{ text }'>
{{ text.substring(0, 10) }}...
</slot>
</div>
</div>
</template>
<script>
export default {
name: 'MyComponent',
props: {
title: String,
},
};
</script>
<p>在上面的代码中,我们定义了一个名为 MyComponent 的组件,其中包含一个 props 属性 title 和一个名为 main 的 slot。在 slot 中,我们使用 slot-scope 属性获取了 slot 内部的数据 text,并对其进行了截取展示。具体来说,我们使用了 JavaScript 字符串的 substring 方法,截取了 text 的前 10 个字符,并在末尾添加了省略号。这样,当组件使用时,我们可以在 main slot 中传入任意文本,并且只会显示前 10 个字符。</p>
原文地址: https://www.cveoy.top/t/topic/lKG5 著作权归作者所有。请勿转载和采集!