一、vue的插槽slot
在
vue
的开发当中,我们可能也经常会使用插槽
slot
,父组件给子组件传递
DOM
元素。插槽的实质,实际上是对于子组件的扩展,通过
slot
插槽向组件内部指定位置传递内容,也是承载内容分发的出口。在这里,以默认插槽、具名插槽和作用域插槽进行总结说明。
二、vue的默认插槽
1. 默认插槽的说明:
默认插槽相当于是在子组件中写明插槽的内容,当父组件在使用子组件的时候,同时父组件没有指定插槽的内容时,那么就使用子组件定义的默认插槽的内容。
2. 代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>默认插槽</title>
<script src="../vue.js"></script>
</head>
<body>
<div id="app">
<child></child>
</div>
<script>
Vue.component('child', {
template: `<div>
<slot>默认内容</slot>
</div>`
})
var vm = new Vue({
el: "#app"
});
</script>
</body>
</html>
三、vue的具名插槽
1. 具名插槽的说明:
具名插槽相当于是在子组件的插槽中给
slot
添加
name
属性,进行命名,在父组件需要使用到插槽的地方,给
slot
添加之前的命名。这样,可以实现向多个组件内部指定位置传递指定的内容。
2. 代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>具名插槽</title>
<script src="../vue.js"></script>
</head>
<body>
<div id="app">
<child>
<div class="header" slot="header">header</div>
<div class="footer" slot="footer">footer</div>
</child>
</div>
<script>
Vue.component('child', {
template: `<div>
<slot name="header">默认内容</slot>
<div class="content">content</div>
<slot name="footer">默认内容</slot>
</div>`
});
var vm = new Vue({
el: "#app"
});
</script>
</body>
</html>
四、vue的作用域插槽
1. 作用域插槽的说明:
作用域插槽相当于是子组件的
DOM
结构由外部传递过来,而使用作用域插槽,子组件可以向父组件传递数据,父组件以
template
模版,通过
slot-scope="props"
进行接收数据,
props.item
就是传递过来的数据。
2. 代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue的作用域插槽</title>
<script src="../vue.js"></script>
</head>
<body>
<div id="app">
<child>
<template slot-scope="props">
<h3>{{ props.item }}</h3>
</template>
</child>
</div>
<script>
Vue.component('child', {
data: function(){
return {
list: [21,22,24,43,29,2,33]
}
},
template: `<div>
<ul>
<slot v-for="item of list" :item=item></slot>
</ul>
</div>`
});
var vm = new Vue({
el: "#app"
});
</script>
</body>
</html>