在 Vue 中使用 v-slot 将 HTML 代码插入 SVG 元素的问题

问题描述 投票:0回答:1

在 Vue 中使用 v-slot 将 HTML 代码插入 SVG 元素的问题

描述:

我使用 v-slot 通过 JavaScript 将 HTML 代码(来自父组件)插入到子组件的 SVG 元素中。

我想在 SVG 中放置一些元素(例如,输入框、图像...),但这取决于父组件向子组件提供的内容。

我必须使用这个函数的原因是我想生成一个数字行并将一些数字替换为html元素。

但是,当我运行代码时,我发现槽元素是空的。看来该插槽没有继承父级的 HTML。但如果我将其放在 SVG 之外,它就可以工作。我使用 V 型槽是否犯了错误?

完整代码在这里: 家长
孩子

这是我的代码的一部分:

父组件:

<template>
  <div>
    <NumberLine>
      <template v-slot>
        <input type="text">
      </template>
    </NumberLine>
  </div>
</template>
<script>
import NumberLine from './NumberLine.vue';

export default {
    components: {
        NumberLine
    },
    name: 'TestParentNode'
};
</script>

子组件:

<template>
  <div class="OutterContainer">
    <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" class="svg"></svg>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'NumberLine',
  mounted() {
    let Svg = document.querySelector('svg');
    Svg.appendChild(this.SvgAddComponent(10, 20));
    
  },
  methods: {
        SvgAddComponent(x, y) {
          let component = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
          component.setAttribute('x', x);
          component.setAttribute('y', y);
          component.setAttribute('width', 30);
          component.setAttribute('height', 30);
          let slot = document.createElement('slot');
          component.appendChild(slot);
          return component;
        }
  }
}
</script>

开发工具信息:

enter image description here

感谢您的耐心等待

javascript vue.js svg
1个回答
0
投票

它应该是这样的:

父组件:

<template>
  <div>
    <NumberLine>
        <input type="text">
    </NumberLine>
  </div>
</template>
<script>
import NumberLine from './NumberLine.vue';

export default {
    components: {
        NumberLine
    },
    name: 'ParentNode'
};
</script> 

子组件:

<template>
  <div class="OutterContainer">
    <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" class="svg">
     <foreignObject x="20" y="20" width="360" height="160">
      <div xmlns="http://www.w3.org/1999/xhtml">
       <slot><slot />
      </div>
     <foreignObject/>
    </svg>
  </div>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.