1、组件中插槽的定义与使用
举例如下:往组件el-hello中插入一个标签
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<el-hello>
<h4>插槽的内容</h4>
</el-hello>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {},
components:{
'el-hello':{
template:`
<div>
<h4>{{name}}</h4>
</div>
`,
props:['datas'],
data:function(){
return{
name:'hello world'
}
}
}
}
})
</script>
</body>
</html>
输出的内容并没有显示组件中的标签,此时插槽的作用就体现出来了
作用:实现父组件往子组件中传递内容
插槽定义:通过< slot></ slot>标签
template: `
<div>
<h4>{{name}}</h4>
<slot></slot> //定义插槽
</div>`
2、具名插槽
定义插槽时,通过name属性给插槽设置一个名字
使用组件时,通过slot指定插槽的名字
注意点:插入多个标签时,通过template来包裹要插入的内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<el-hello>
<template slot='demo1'>
<h4>插槽1中的内容</h4>
<h4>插槽1中的内容</h4>
</template>
<template slot='demo2'>
<h4>插槽2中的内容</h4>
<h4>插槽2中的内容</h4>
</template>
</el-hello>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {},
components: {
'el-hello': {
template: `
<div>
<slot name='demo1'></slot>
<h4>{{name}}</h4>
<slot name='demo2'></slot>
</div>
`,
props: ['datas'],
data: function() {
return {
name: 'hello world'
}
}
}
}
})
</script>
</body>
</html>