Vue.js 教程

Vue.js 组件应用插槽

和 HTML 元素一样,我们经常需要向一个组件传递内容,像这样:

<alert-box>
    Something bad happened.
</alert-box>

可能会渲染出这样的效果:

幸好,Vue 自定义的 <slot> 元素让这变得非常简单:

Vue.component('alert-box', {
   template: `
       <div class="demo-alert-box">
           <strong>Error!</strong>
           <slot></slot>
       </div>
   `
})

如你所见,我们只要在需要的地方加入插槽(slot)就行了 —— 就这么简单!

完整示例

<html>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Vue</title>
   <!-- 使用 CDN 引入 Vue 库 -->
   <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> -->
   <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.js"></script>
</head>
<body>

   <div id="app">
       <alert-box>Something bad happened.</alert-box>
       <alert-box>
           <span style="color:red;">Something bad happened.</span>
       </alert-box>
   </div>

   <script type="text/javascript">
       // 定义文章相组件
       Vue.component('alert-box', {
           template: `
               <div>
                   <strong>Error!</strong>
                   <slot></slot>
               </div>
           `
       });

       var app = new Vue({
           el: "#app",
           data: {}
       });
   </script>

</body>
</html>

效果如下图:

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号