之前的文章我们介绍了一下 vue 中插槽的使用, 本章我们接着介绍一下 vue 中的作用域插槽.
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- vue
- </title>
- <script src="https://cdn.jsdelivr.net/npm/vue">
- </script>
- </head>
- <body>
- <div id="app">
- <child>
- </child>
- </div>
- <script>
- Vue.component("child", {
- data() {
- return {
- list: ["aaa", "bbb", "ccc"]
- }
- },
- template: ` < div > <p v -
- for = "(item,index) of list": key = "index" > {
- {
- item
- }
- } < /p>
- </div > `
- });
- var App = new Vue({
- el: '#app',
- })
- </script>
- </body>
- </HTML>
在上面的代码中我们在子组件 child 中定义了一个 list 的数据, 然后通过循环输出的形式把每一项输出在了一个 <p> 标签内, 结果如下:
上面的代码显然符合我们之前的预期, 但是现在有一个问题, 我想让 list 数组内的数据不是放在 <p> 标签内, 而是放在一个 <h1> 标签内, 那这样的话我们就需要将 template 内的 <p> 标签换为 <h1> 标签, 但是别的地方却需要使用 <p> 标签输出, 这该怎么办, 我们总不能写两个不同的子组件吧, 官方为我们提供了作用于插槽来解决这个问题, 如下:
- <!DOCTYPE HTML>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- vue
- </title>
- <script src="https://cdn.jsdelivr.net/npm/vue">
- </script>
- </head>
- <body>
- <div id="app">
- <child>
- <template slot-scope="props">
- <h1>
- {{props.item}}
- </h1>
- </template>
- </child>
- </div>
- <script>
- Vue.component("child", {
- data() {
- return {
- list: ["aaa", "bbb", "ccc"]
- }
- },
- template: ` < div > <slot v -
- for = "(item,index) of list": key = "index": item = "item" > {
- {
- item
- }
- } < /slot>
- </div > `
- });
- var App = new Vue({
- el: '#app',
- })
- </script>
- </body>
- </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> 标签即可, 不需要再去改动子组件.
来源: https://www.cnblogs.com/weijiutao/p/10683646.html