详解Vue.js 作用域、slot用法(单个slot、具名slot)

2020-06-12 20:52:59易采站长站整理

作用域

在介绍slot前,需要先知道一个概念:编译的作用域。比如父组件中有如下模板:


<child-component>
{{message}}
<child-component>

这里的message就是一个slot,但是它绑定的是父组件的数据,而不是组件

< child-component >
的数据。

父组件模板的内容是在父组件作用域内编译,子组件模板的内容是在子组件作用域内编译。


<div id="app">
<child-component v-show="showChild"></child-component>
</div>
<script>
Vue.component('child-component',{
template: '<div>子组件</div>'
});

var app = new Vue({
el: '#app',
data: {
showChild: true
}
});
</script>

这里的状态showChild绑定的是父组件的数据,如果想在子组件上绑定,那应该是:


<div id="app">
<child-component></child-component>
</div>
<script>
Vue.component('child-component',{
template: '<div v-show="showChild">子组件</div>',
data: function () {
showChild: true
}
});

var app = new Vue({
el: '#app'
});
</script>

因此,slot分发的内容,作用域是在父组件上的。

slot用法

单个slot:

在子组件使用特殊的< slot >元素就可以为这个子组件开启一个 slot(插槽),在父组件模板里,插入在子组件标签内的所有内容将替代子组件的< slot >标签及它的内容。


<!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">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>单个slot</title>
</head>
<body>
<div id="app">
<cild-component>
<p>分发的内容</p>
<p>更多分发的内容</p>
</cild-component>
</div>
<script>
Vue.component('child-component',{
template: '
<div>
<slot>
<p>如果父组件没有插入内容,我将作为默认出现</p>
</slot>
</div>'
});

var app = new Vue({
el: '#app'
});
</script>
</body>
</html>

子组件child-component的模板内定义了一个< slot >元素,并且用一个< p >作为默认的内容,在父组件没有使用slot时,会渲染这段默认的文本;如果写入了slot,那就会替代整个< slot >标签。