Won*_*man 5 javascript vue.js contentful nuxt.js
我正在和Contentful一起玩!我在使用富文本内容字段时遇到问题。
我使用“@contentful/rich-text-types”和@contentful/rich-text-html-renderer模块来自定义此块的呈现方式,并显示富文本内容中链接的一些资源和参考。
在 nuxt asyncData 函数中调用 getEntries 后,我的页面组件中有一个可用的描述数据。我正在使用带有选项的 documentToHtmlString 函数。
一切工作正常,但我想使用我已经编写的组件(Post.vue),而不是在 ES6 模板字符串中返回模板。
我知道这是可能的,但我对 JS 世界还很陌生。
我尝试要求 Components/post/Post.vue,但我不知道如何使用它。
import { BLOCKS } from '@contentful/rich-text-types';
import { documentToHtmlString } from "@contentful/rich-text-html-renderer"
Run Code Online (Sandbox Code Playgroud)
渲染富文本字段的 Vue 组件模板
<section class="container">
<div class="columns">
<div class="column">
<div v-html="formatContent(description)" />
</div>
</div>
</section>
Run Code Online (Sandbox Code Playgroud)
我只需调用 formatContent 方法来调用 documentToHtmlString,如下所示(它有效):
methods: {
formatContent(content) {
return documentToHtmlString(content, options)
}
}
Run Code Online (Sandbox Code Playgroud)
并使用文档中描述的选项自定义 documentToHtmlString:
const embeddedEntryRender = (node) => {
const { data: { target: entry} } = node
const fields = entry.fields
const sys = entry.sys
// LOOK HERE
// const postComponent = require('~/components/post/Post')
return `
<div class="column is-4">
<div class="card">
<div class="card-content">
<div class="media">
<div class="media-content">
<h3 class="title is-4">${fields.title}</h3>
<div class="subtitle is-6">${fields.description}</div>
</div>
</div>
<div class="content">
</div>
</div>
</div>
</div> `
}
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ENTRY]: (node) => embeddedEntryRender(node),
// [BLOCKS.EMBEDDED_ASSET]: (node) => `<custom-component>${customComponentRenderer(node)}</custom-component>`
}
}
Run Code Online (Sandbox Code Playgroud)
未检测到错误
--
多谢
小智 3
是的,你可以在其中使用一个自定义的 vue 组件和不同的 npm 库,我也遇到了同样的问题。
npm i contentful-rich-text-vue-renderer
Run Code Online (Sandbox Code Playgroud)
在模板中:
<rich-text-renderer :document="document" :nodeRenderers="renderNode" />
Run Code Online (Sandbox Code Playgroud)
其中“文档”是发送形式内容丰富的数据,看起来像您所说的描述。RenderNode是下面描述的方法。
在脚本中:
data () {
return {
renderNode: [INLINES.ASSET_HYPERLINK]: (node, key, h) => {
return h('my-vue-component', { key: hey, props: { myProp: 'blah blah' }},'what I want inside the <my-vue-component> tag'`)
}
}
Run Code Online (Sandbox Code Playgroud)
这可能有点令人困惑。因此,首先从该 npm 库导入 richTextRenderer 组件,并确保在 vue 组件的组件部分中声明它。(或洋洋自得地)
接下来将内容丰富的富文本字段传递到其“文档”属性中
如果你想要自定义渲染,请传递给 nodeRenders prop 一个函数(我必须在数据部分声明它)
我的示例采用任何资产超链接类型并将其替换为我想要的标签内的组件
只有当我在 main.js 文件中全局声明 my-vue-component 时,我才能使其正常工作。
import MyVueComponent from 'wherever/it/is';
Vue.component('my-vue-component', MyVueComponent);
Run Code Online (Sandbox Code Playgroud)
还有更多配置,只需阅读 npm libs 文档(虽然它不是很好的文档,但我花了很长时间才弄清楚如何传递 props,我必须阅读他们的 github 代码才能弄清楚,哈哈)