在 Vue.js 中使用自定义渲染函数创建文本节点 [英] Create text node with custom render function in Vue.js

查看:27
本文介绍了在 Vue.js 中使用自定义渲染函数创建文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 my-link 组件根据需要将锚标记包装在各种项目周围.为此,使用了自定义 render 方法 - 但是 createElement 方法只能创建 HTML 节点,创建纯文本节点似乎是不可能的.

I'm using a my-link component to wrap an anchor tag on demand around various items. For that purpose a custom render method is used - however the createElement method can only create HTML nodes, creating plain text nodes does not seem to be possible.

<template v-for="item in items">
  <h4>
    <my-link :url="item.url">{{ item.text }}</my-link>
  </h4>
</template>

my-link 组件实现为Link.vue

Implementation of my-link component as 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>

结果 HTML

<h4>
  <a url="/some-link">This item is linked</a>
</h4>
<h4>
  <span>Plain text item</span>
</h4>

预期场景

span 标签在这个特定场景中是多余的,可以避免 - 但是,我不清楚 Vue.js 如何以及是否完全可以做到这一点.一般来说,我想知道如何使用自定义 render 方法创建纯文本节点.

Desired scenario

The span tag in this particular scenario is superfluous and could be avoided - however, it's not clear to me, how and whether at all this is possible with Vue.js. In general, I'd like to know how to create plain text nodes using a custom render method.

<h4>
  <a url="/some-link">This item is linked</a>
</h4>
<h4>
  Plain text item
</h4>


旁注:


Side-notes:

  • 问题最初是针对 VueJS v2.1 & 提出的.v2.2-beta(2017 年 2 月)
  • 关注正确的语义节点(文本节点与元素节点)

推荐答案

Vue 在其原型上公开了一个名为 _v 的内部方法,该方法创建了一个纯文本节点.您可以从渲染函数返回调用此方法的结果以渲染纯文本字符串:

Vue exposes an internal method on it's prototype called _v that creates a plain text node. You can return the result of calling this method from a render function to render a plain text string:

render(h){
    return this._v("my string value");
}

以这种方式公开它,并以下划线为前缀,可能表明它旨在作为私有 API 方法,因此请谨慎使用.

Exposing it in this way, prefixed with an underscore, likely indicates it's intended as a private API method, so use with care.

如果使用功能组件,this"也不可用.在这种情况下,您应该调用 context._v(),例如:

If you use a functional component, "this" is also not available. In this case, you should call context._v(), for example:

functional: true,
render(h, context){
    return context._v("my string value")
}

结合从插槽中提取文本(如您的评论中所示,使用有用的 getChildrenTextContent) 将产生所需的结果.

This, combined with extracting the text from the slot (as in your comment, using the helpful getChildrenTextContent) will produce the desired result.

这篇关于在 Vue.js 中使用自定义渲染函数创建文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆