【问题标题】:Slot stops after certain child element in Vue2在 Vue2 中的某个子元素之后,插槽停止
【发布时间】:2022-02-06 17:40:05
【问题描述】:

我有两个简单的 vue 组件,想在另一个的默认插槽中使用一个。由于某种原因,它只需要第一个元素,但之后不显示任何内容。如果我把标准放在第一个元素之前,它会正常显示,但如果我放在 if 之后,它也不会显示。

页面:

<div id="app">
    <v-app>
        <v-main>
            <gantt-chart>
                <div> this is visible </div>
                <gantt-row key="1" title="test 1"/> 
                <div> nothing of this and beyond is shown</div>
                <gantt-row key="2" title="test 2"/> 
                <gantt-row key="3" title="test 3"/> 
            </gantt-chart>
        </v-main>
    </v-app>
</div>
<script type="text/javascript">
    Vue.component("gantt-chart", httpVueLoader('/plugin_assets/javascripts/components/GanttChart.vue'));
    Vue.component("gantt-row", httpVueLoader('/plugin_assets/javascripts/components/GanttRow.vue'));
    var app = new Vue({
        el: '#app',
    })
</script> 

甘特图.vue:

<template>
    <div>
      <slot />
    </div>
</template>

<script>
module.exports = {
  props: [],
  name:"GanttChart",
  data() {
    return {};
  },
  computed: {},
  methods: {},
};
</script>

<style scoped></style>

甘特行.vue:

<template>
    <div>
      {{ title }}
    </div>
</template>

<script>
module.exports = {
  props: ["title"],
  name:"GanttRow",
  data() {
    return {};
  },
  computed: {},
  methods: {},
};
</script>

<style scoped></style>

结果:

【问题讨论】:

    标签: javascript html vue.js vuejs2 http-vue-loader


    【解决方案1】:

    DOM 内模板的一个警告是自定义元素不能自动关闭。 DOM 解析器看到&lt;gantt-row /&gt;,但仅将其视为开始标记。由于标签在技术上尚未关闭,因此它将以下元素包装为子元素。 GanttRow.vue 的模板没有&lt;slot&gt;,因此嵌套元素将不可见。这一切都发生在 脚本阶段之前(在 Vue 接收 DOM 以进行模板处理之前)。

    例如,运行下面的代码 sn-p,并检查生成的文档:

    <div> this is visible </div>
    <gantt-row key="1" title="test 1"/>
    <div> nothing of this and beyond is shown</div>
    <gantt-row key="2" title="test 2"/>
    <gantt-row key="3" title="test 3"/>

    你会注意到变成:

    <div> this is visible </div>
    <gantt-row key="1" title="test 1">
      <div> nothing of this and beyond is shown</div>
      <gantt-row key="2" title="test 2">
        <gantt-row key="3" title="test 3">
          <script type="text/javascript"></script>
        </gantt-row>
      </gantt-row>
    </gantt-row>
    

    如果您希望继续使用 DOM 内模板,请为 Vue 组件使用普通的结束标记:

    <gantt-chart>
      <div> this is visible </div>           ?
      <gantt-row key="1" title="test 1"></gantt-row>
      <div> everything below is also shown now </div>
                                             ?
      <gantt-row key="2" title="test 2"></gantt-row>
                                             ?
      <gantt-row key="3" title="test 3"></gantt-row>
    </gantt-chart>
    

    【讨论】:

      猜你喜欢
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多