需求
上一篇章,我们讲解了Vue中插槽的基本使用方法,本篇章来讲解作用域查看的情况。这是一种什么情况呢?
简单来说就是使用 v-for 渲染插槽的数据传递情况,下面来具体示例说明一下。
示例说明
首先编写一个基础的代码,编写好一个子组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue中作用域插槽slot</title>
<!-- 1.导入vue.js -->
<script src="lib/vue.js"></script>
</head>
<body>
<!-- 2.创建app -->
<div id="app">
<child></child>
</div>
<!-- 3.创建vm -->
<script>
Vue.component("child", {
template: `<div>
<ul>
<li v-for="item in list">{{item}}</li>
</ul>
</div>`,
data(){
return {
list: [1,2,3,4,5,6]
}
},
});
let vm = new Vue({
el: "#app",
data: {},
})
</script>
</body>
</html>
在上面的代码中,子组件中的 ul 使用 v-for 遍历了一个 li 的结构,页面效果如下:
image-20200727220506941看到了这个结构之后,我们就可以理所当然地提出一个关于插槽方面的需求了。
作用域插槽的需求
如果我们想要遍历的并不是简单的 li 结构,而是希望在父元素编写来形成的 dom 结构,但是又需要从子组件中的数据来遍历。
那么如何将子组件的 data 数组传递到 父组件,然后让父组件来遍历编写 dom 结构呢?
作用域插槽的实现
第一步,首先将子组件的数据绑定到插槽 slot 的属性上
Vue.component("child", {image-20200727221047363
template: `<div>
<ul>
<slot v-for="item in list" v-bind:item="item"></slot>
</ul>
</div>`,
data(){
return {
list: [1,2,3,4,5,6]
}
},
});
第二步,使用 template 便签渲染 slot 插槽
<child>image-20200727221155101
<template slot-scope="props">
<li>{{props.item}} -- hello</li>
</template>
</child>
注意:
- 必须使用 template 标签编写
- 使用 slot-scope="props" 可以接收子组件绑定的数据
浏览页面效果如下:
image-20200727221340940那么此时遍历的效果就取决于父组件了。
作用域插槽的 vue 2.6 更新写法
上面已经基本实现了作用域插槽的基本使用,但是在 vue 2.6 版本开始,通过 slot-scope 的属性方式获取 props 值将会被逐步废弃。
更新的写法如下:
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
-
v-slot 绑定一个 slot 的命名 name,并且绑定子组件设置的参数。
-
其中 default 为默认的 slot 命名
修改一下上面的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue中作用域插槽slot</title>
<!-- 1.导入vue.js -->
<script src="lib/vue.js"></script>
</head>
<body>
<!-- 2.创建app -->
<div id="app">
<child>
<template v-slot:default="props">
<li>{{props.item}} -- hello</li>
</template>
</child>
</div>
<!-- 3.创建vm -->
<script>
Vue.component("child", {
template: `<div>
<ul>
<slot v-for="item in list" v-bind:item="item"></slot>
</ul>
</div>`,
data(){
return {
list: [1,2,3,4,5,6]
}
},
});
let vm = new Vue({
el: "#app",
data: {},
})
</script>
</body>
</html>
更多精彩原创Devops文章,快来关注我的公众号:【Devops社群】 吧:」
image
点击下面,查看更多Vue系列文章