首页 > 解决方案 > Vue.js - 命名槽

问题描述

我有一个关于命名插槽的初学者问题。在我的示例中,我只想显示第一个插槽的内容 - 但除非我<slot></slot>不使用name="first". 我的例子有什么问题?

Vue.component('user-name', {
  props: ['name'],
  template: `
  	     <p slot="first">Hi {{ name }}</p>
            `
});

Vue.component('user-nickname', {
  props: ['name'],
  template: `
             <p slot="secont">Byee {{ name }}</p>
            `
});

Vue.component('user-information', {
  template: `<div class="user-information">
	         <slot name="first"></slot>								
              </div>
             `,
});

new Vue({
  el: "#app"
});
body{
  width:700px;
  margin:0 auto;
  text-align:center;
  color: blue;
  
}

.user-information {
  background: red;
  width: 700px;
  height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <user-information>
      <user-name name="Foo"></user-name>
      <user-nickname name="Boo"></user-nickname>
    </user-information>
</div>

标签: vue.jsvue-component

解决方案


slot="..whatever.."从您的组件中删除。然后将第二个命名槽添加到user-information. 最后在您的主要参考中,插槽作为子组件的父级

<user-information>
    <template v-slot:first>
        <user-name name="Foo"></user-name>
    </template>
    <template v-slot:second>
        <user-nickname name="Boo"></user-nickname>
    </template>
</user-information>

推荐阅读