返回
从Sanity获取干净的正文文本:告别杂乱无章,拥抱可读性!
vue.js
2024-03-18 03:00:49
如何从 Sanity 中获取干净的正文文本
问题陈述
从 Sanity 中获取正文文本时,经常会遇到拉取到不必要的元素的问题。这会使输出结果杂乱无章,难以阅读。
解决方法
解决此问题的方法是使用 body.children
而不是 body
。body.children
返回一个包含所有正文块的数组。然后,你可以循环遍历这些块并提取文本内容。
let bodyText = "";
post.body.children.forEach((block) => {
bodyText += block.text;
});
代码示例
以下是更新后的代码示例:
<template>
<Header />
<h1>This is the blog page!</h1>
<div v-for="post in posts" :key="post._id" class="post">
<div class="post-img">
<img :src="$urlFor(post.mainImage).url()" :alt="`${post.title}`" />
</div>
<div class="post-text">
<div class="post-text__title">
<a :href="`${post.slug.current}`"
><h2>{{ post.title }}</h2></a
>
</div>
<div class="post-text__description">
<p>{{ bodyText }}</p>
</div>
</div>
</div>
</template>
<script setup>
const query = groq`*[ _type == "post" ]{title, slug, mainImage, body} | order(_publishedAt desc)`;
const { data: posts } = await useSanityQuery(query);
let bodyText = "";
posts.forEach((post) => {
post.body.children.forEach((block) => {
bodyText += block.text;
});
});
</script>
通过使用这种方法,你将仅提取正文文本,而不会出现任何不必要的元素。
结论
了解 Sanity 中的块级内容的结构非常重要。通过使用 body.children
并提取文本内容,你可以获得干净、可读的正文文本。这将极大地改善你从 Sanity 中拉取数据的体验。
常见问题解答
- 为什么我从 Sanity 中获得不必要的文本?
这是因为正文字段实际上是一个包含各种元素的块级内容集合。
body.children
是什么?
body.children
是一个包含所有正文块的数组。
- 如何从块级内容中提取文本?
你可以循环遍历块级内容数组并从每个块中提取文本。
- 如何更新我的模板以获取干净的文本?
更新你的模板以使用 body.children
而不是 body
。
- 有没有其他方法可以获取干净的文本?
没有其他内置方法可以从 Sanity 中获取干净的文本。但是,你可以编写自己的函数来处理块级内容并提取文本。