我正在使用一个my-link
组件来根据需要包装各种项目的锚标签.为此目的,使用自定义render
方法 - 但是该createElement
方法只能创建HTML节点,创建纯文本节点似乎不可能.
my-link
组件的用法<template v-for="item in items">
<h4>
<my-link :url="item.url">{{ item.text }}</my-link>
</h4>
</template>
Run Code Online (Sandbox Code Playgroud)
my-link
组件的实现为Link.vue
<script>
export default {
name: 'my-link',
props: { url: String },
render(createElement) {
if (this.url) {
return createElement(
'a', {
attrs: { href: this.url }
}, this.$slots.default
);
}
return createElement(
'span',
this.$slots.default
);
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
<h4>
<a url="/some-link">This item is linked</a>
</h4>
<h4>
<span>Plain text item</span>
</h4>
Run Code Online (Sandbox Code Playgroud)
span
这个特殊场景中的标签是多余的,可以避免 - 但是,我不清楚如何以及是否可以使用Vue.js.一般来说,我想知道如何在自定义render
方法中创建纯文本节点.
<h4>
<a url="/some-link">This item is linked</a>
</h4>
<h4>
Plain text item
</h4>
Run Code Online (Sandbox Code Playgroud)
Ber*_*ert 16
Vue 在它的原型上公开了一个内部方法,称为_v,它创建了一个纯文本节点.您可以从render函数返回调用此方法的结果,以呈现纯文本字符串:
render(h){
return this._v("my string value");
}
Run Code Online (Sandbox Code Playgroud)
以这种方式公开它,以下划线为前缀,可能表明它打算作为私有API方法,因此请小心使用.
如果使用功能组件,则"此"也不可用.在这种情况下,您应该调用context._v(),例如:
functional: true,
render(h, context){
return context._v("my string value")
}
Run Code Online (Sandbox Code Playgroud)
这与从插槽中提取文本(如在评论中,使用有用的getChildrenTextContent)相结合将产生所需的结果.
归档时间: |
|
查看次数: |
4785 次 |
最近记录: |