Vue.js 2 VNode数组怎么插入到某个元素下?

自定义了一个组件: A,通过slot拿到A开始标签与结束标签之间内容. 通过:
this.$slots.default
拿到一个VNode数组,
问题1: 有什么方法拿到Dom的InnerHTML吗?

以下的组件A的大致结构:

<template>
  <el-popover trigger="hover" placement="top" ref="fullText">
    {{ fullText }}
    <div slot="reference" v-bind:style="styleObject">
      <slot></slot>
    </div>
  </el-popover>
</template>

问题2: 若无法拿到InnerHTML的前提下该如何将VNode数组放到组件的某个元素(ref=fullText)中呢?

附上组件A(ellipsis-tip)的调用示例.

                  <ellipsis-tip :style-obj="{lineHeight:'36px',height:'36px',fontSize:'12px'}">
                    符合条件企业:<em class="red-c">{{ statisticsb.applyCount }}</em>家,
                    注册资本/出资额合计<em class="red-c">{{ statisticsb.fundCHN }}</em>亿元/
                    <em class="red-c">{{ statisticsb.fundUSA }}</em>亿美元,
                    实缴注册资本/出资额<em class="red-c">{{ statisticsb.currentFundCHN }}</em>亿元/
                    <em class="red-c">{{ statisticsb.currentFundUSA }}</em>亿美元,
                    管理规模合计<em class="red-c">{{ statisticsb.fundamoutCHNHN }}</em>亿元/
                    <em class="red-c">{{ statisticsb.amoutUSA }}</em>亿美元,
                    从业人数<em class="red-c">{{ statisticsb.staffSize }}</em>人
                  </ellipsis-tip>

说明. statisticsb是在页面加载后异步计算的统计数据

阅读 2.3k
1 个回答
✓ 已被采纳

很高兴这个问题我也挺感兴趣,于是尝试着解决,有如下方法:

问题1:

<template>
  <el-popover trigger="hover" placement="top" ref="fullText">
    {{ fullText }}
    <div slot="reference">
      <slot></slot>
    </div>
  </el-popover>
</template>

<script>
import Vue from "vue";
import nodeRenderer from "./RenderNode";
const DetailConstructor = Vue.extend(nodeRenderer);
export default {
  props: {
    fullText: "",
  },
  mounted() {
    // 方案1 - 参考 https://stackoverflow.com/a/50937178/3089701
    const detailRenderer = new DetailConstructor({
      propsData: {
        node: this.$slots.default,
      },
    });
    console.log(detailRenderer.$mount(), detailRenderer.$el.outerHTML); // $el是dom对象,任意操作
    // 方案2 - 也是参考上面的,拿到完整的dom,如果只需要该组件slot的后面
    const slot = this.$slots.default[0];
    console.log(slot.context.$mount(), slot.context.$el.innerHTML);
  },
};
</script>

对应的RenderNode.js

export default {
  props: ['node'],
  render(h, context) {
      return this.node ? this.node : ''
  }
}

我参考了代码中注释部分的资料总结。


问题2:

既然拿到DOM了,我想你应该也知道如何操作了。。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题