Vue插槽使用
概述
插槽就是子组件中用slot标签定义的预留位置,可以设置name属性,也可以不设置name属性,设置name的叫具名插槽
,不设置name的的叫不具名插槽
,在父组件中使用子组件时候可以在使用子组件的标签内
通过声明插槽名
或不声明插槽名
的方式往子组件中的具名插槽
或者不具名插槽
写入html代码
。
插槽使用的关键在于:在父组件中使用子组件标签的时候可以往子组件内写入html代码
。
使用步骤
- 子组件中定义插槽
- 父组件使用子组件时往插槽写入代码
核心伪代码
父组件视图中:
<子组件名>
<!--往插槽写入html代码-->
<!--写入具名插槽1-->
<div slot="插槽名1">
这段html连带div会写入到子组件插槽名1
</div>
<!--写入具名插槽2-->
<template slot="插槽名2">
由于template不会被解析,所以这段html只有这段文字会写入到子组件插槽名2
</template>
<!-- 写入不具名插槽 -->
<template>
这段文字会写入不具名插槽
</template>
</子组件名>
子组件视图:
<h2>子组件</h2>
<!--定义插槽-->
<!--slot设置了name属性为具名插槽,不设置name属性为不具名插槽-->
<!--具名插槽-->
<slot name="插槽名2"></slot>
<slot name="插槽名1"></slot>
<!--不具名插槽-->
<slot></slot>
总结:
- 插槽在子组件的视图中定义
子组件视图:
<h2>子组件</h2>
<!--slot设置了name属性为具名插槽,不设置name属性为不具名插槽-->
<!--具名插槽-->
<slot name="插槽名2"></slot>
<slot name="插槽名1"></slot>
<!--不具名插槽-->
<slot></slot>
- 父组件使用子组件标签时,可以通过使用template标签或者其他html标签并设置slot属性为插槽名来将标签内容写入指定的插槽,也可以不设置slot属性表示将内容写入不具名插槽中。
<子组件标签>
<!--写入具名插槽1-->
<div slot="插槽名1">
这段html连带div会写入到子组件插槽1位置
</div>
<!--写入具名插槽2-->
<template slot="插槽名2">
由于template不会被解析,所以这段html只有这段文字会写入到子组件插槽2位置
</template>
<!-- 写入不具名插槽 -->
<template>
这段文字会写入不具名插槽
</template>
</子组件标签>
实际代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<template id="temp">
<div class="child">
<h2>子组件</h2>
<!--slot设置了name属性为具名插槽,不设置name属性为不具名插槽-->
<!--具名插槽-->
<slot name="slot2"></slot>
<slot name="slot1"></slot>
<!--不具名插槽-->
<slot></slot>
</div>
</template>
<div id="app">
<child>
<!--写入具名插槽1-->
<div slot="slot1">
这段html连带div会写入到子组件插槽名1
</div>
<!--写入具名插槽2-->
<template slot="slot2">
由于template不会被解析,所以这段html只有这段文字会写入到子组件插槽名2
</template>
<!-- 写入不具名插槽 -->
<template>
这段文字会写入不具名插槽
</template>
</child>
</div>
<script src="../js/vue.js"></script>
<script>
Vue.component('child', {
template: '#temp',
})
var vm = new Vue({
el: '#app',
})
</script>
</body>
</html>
父组件中使用插槽需要获取子组件中的数据
父组件往插槽中写入的html代码中,如果需要用到子组件的数据的话,就需要用到slot-scope了。slot-scope这个不难,但需要对组件以及插槽的定义与使用比较熟练才能很好理解其作用。
slot-scope使用步骤
- 子组件定义插槽并使用v-bind设置数据
比如<slot name="slot1" :msg1="信息1" :msg2="信息2"></slot>
- 父组件使用插槽时设置设置标签的slot-scope属性为一个值
这个值是第一步绑定数据为属性组成的对象,{msg1:‘信息1’, msg2:‘信息2’}
伪代码
父组件视图中:
<子组件名>
<!--写入具名插槽1-->
<div slot="slot1" slot-scope="scope">
这段html连带div会写入到子组件插槽名1,下面我将使用scope来获取子组件定义slot时候传递的数据:
{scope.name1}
{scope.name2}
</div>
</子组件名>
子组件视图中:
<子组件名>
<slot name="slot1" :name1="'罗小黑'" :name2="'罗中黑'"></slot>
</子组件名>
实际代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<template id="temp">
<div class="child">
<h2>子组件</h2>
<slot name="slot1" :name1="'罗小黑'" :name2="'罗中黑'"></slot>
</div>
</template>
<div id="app">
<child>
<!--写入具名插槽1-->
<div slot="slot1" slot-scope="scope">
这段html连带div会写入到子组件插槽名1,下面我将使用scope来获取子组件定义slot时候传递的数据:
<br>
{{scope.name1}}
<br>
{{scope.name2}}
</div>
</child>
</div>
<script src="../js/vue.js"></script>
<script>
Vue.component('child', {
template: '#temp',
})
var vm = new Vue({
el: '#app',
})
</script>
</body>
</html>