Vue 进阶之路(十二)

之前的文章我们介绍了一下 vue 中插槽的使用,本章我们接着介绍一下 vue 中的作用域插槽。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>vue</title>
 6     <script src="https://cdn.jsdelivr.net/npm/vue"></script>
 7 </head>
 8 <body>
 9 <div id="app">
10     <child></child>
11 </div>
12 <script>
13     Vue.component("child", {
14         data() {
15             return {
16                 list: ["aaa", "bbb", "ccc"]
17             }
18         },
19         template: `
20             <div>
21                 <p v-for="(item,index) of list" :key="index">{{item}}</p>
22             </div>
23        `
24     });
25     var app = new Vue({
26         el: '#app',
27     })
28 </script>
29 </body>
30 </html>

在上面的代码中我们在子组件 child 中定义了一个 list 的数据,然后通过循环输出的形式把每一项输出在了一个 <p> 标签内,结果如下:

上面的代码显然符合我们之前的预期,但是现在有一个问题,我想让 list 数组内的数据不是放在 <p> 标签内,而是放在一个 <h1> 标签内,那这样的话我们就需要将 template 内的 <p> 标签换为 <h1> 标签,但是别的地方却需要使用 <p> 标签输出,这该怎么办,我们总不能写两个不同的子组件吧,官方为我们提供了作用于插槽来解决这个问题,如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>vue</title>
 6     <script src="https://cdn.jsdelivr.net/npm/vue"></script>
 7 </head>
 8 <body>
 9 <div id="app">
10     <child>
11         <template slot-scope="props">
12             <h1>{{props.item}}</h1>
13         </template>
14     </child>
15 </div>
16 <script>
17     Vue.component("child", {
18         data() {
19             return {
20                 list: ["aaa", "bbb", "ccc"]
21             }
22         },
23         template: `
24             <div>
25                 <slot v-for="(item,index) of list" :key="index" :item="item">{{item}}</slot>
26             </div>
27        `
28     });
29     var app = new Vue({
30         el: '#app',
31     })
32 </script>
33 </body>
34 </html>

我们将 template 内的 <p> 标签变为 <slot> 标签,然后在 <slot> 标签内加上一个 :item="item" 的属性,意思是将 item 内容通过 :item="" 的形式展示出去。

在 <child> 标签内加入一个 <template> 标签,标签内加入 slot-scope="props",意思是通过 slot-scope="scope" 将 template 内的 slot 进行连接。

然后输出 <h1>{{props.item}}</h1> ,意思是将连接的 slot 内的展示出来的 :item 内的值展示出来,并且展示在 <h1> 标签内。

运行结果如下:

符合我们的预期,这样我们如果想让输出内容放在 <p> 标签内,只需要将 <h1> 标签改为 <p> 标签即可,不需要再去改动子组件。

猜你喜欢

转载自www.cnblogs.com/weijiutao/p/10683646.html