【问题标题】:Simple Vue slot example not working简单的 Vue 插槽示例不起作用
【发布时间】:2018-08-15 14:17:38
【问题描述】:

我正在尝试了解 <slot> 在 Vue 模板中的用法。据我了解,插槽可用于将组件中的子内容传递给模板。

下面是一个简短的、最小的工作示例 (also on codepen)。

Vue.component('mine', {
  template: '#mine'
})

var app = new Vue({
  el: '#app' 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>

<script type="text/x-template" id="mine">
  <h1>this is it</h1>
  <slot></slot>
</script>

<div id="app">
  <mine>
    <p>why isn't this displayed</p>
  </mine>
</div>

我希望输出是这样的:

<h1>this is it</h1>
<p>why isn't this displayed</p>

但是,当页面被渲染时,第二行没有出现。

【问题讨论】:

  • 试试

标签: vue.js vue-component


【解决方案1】:

模板需要有一个根 DOM 元素。看起来 Vue 只是将 h1 作为整个模板并丢弃其余部分:

Vue.component('mine', {
  template: '#mine'
})

var app = new Vue({
  el: '#app' 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>

<script type="text/x-template" id="mine">
  <div>
    <h1>this is it</h1>
    <slot></slot>
  </div>
</script>

<div id="app">
  <mine>
    <p>why isn't this displayed</p>
  </mine>
</div>

(使用库的“开发者模式”版本会给你更好的关于这类事情的错误消息:)

Vue.component('mine', {
  template: '#mine'
})

var app = new Vue({
  el: '#app' 
})
<script src="https://vuejs.org/js/vue.js"></script>

<script type="text/x-template" id="mine">
    <h1>this is it</h1>
    <slot></slot>
</script>

<div id="app">
  <mine>
    <p>why isn't this displayed</p>
  </mine>
</div>

【讨论】:

  • 感谢关于开发构建的提示;这非常有帮助。在尝试学习 Vue 的过程中,我发现了许多不起作用但也不会引发错误或警告的东西。
  • 是的,vue 中的开发模式有异常好的错误信息;我希望其他框架也能像这样关心这类事情。
猜你喜欢
  • 2019-09-15
  • 1970-01-01
  • 2012-07-01
  • 2015-11-23
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
相关资源
最近更新 更多