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

作用域

在介绍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: '
子组件
'
}); 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: '
子组件
'
, data: function () { showChild: true } }); var app = new Vue({ el: '#app' });
script>

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

slot用法

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


<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>单个slottitle>
head>
<body>
    <div id="app">
        <cild-component>
            <p>分发的内容p>
            <p>更多分发的内容p>
        cild-component>
    div>
    <script>
        Vue.component('child-component',{
            template: '\
                
\ \

如果父组件没有插入内容,我将作为默认出现

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

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

上面示例渲染后的结果为:

<div id="app">
	<div>
		<p>分发的内容p>
		<p>更多分发的内容p>
	div>
div>

注意:子组件< slot >内的为备用内容,它的作用域是子组件本身。

具名slot:
给< slot >元素指定一个name后可以分发多个内容,具名slot可以与单个slot共存。

<div id="myApp">
    <child-component>
        <h2 slot="header">标题h2>
        <p>正文内容p>
        <p>更多的正文内容p>
        <div slot="footer">底部信息div>
    child-component>
div>
<script>
    Vue.component('child-component',{
        template: '\
            
\
\ \
\
\ \
\ \
'
}); var myApp = new Vue({ el: '#myApp' });
script>

子组件内声明了3个< slot >元素,其中在< div class=“main” > 内的 < slot >没有使用name特性,它将作为默认slot出现,父组件没有使用slot特性的元素与内容都将出现在这里。

如果没有制定默认的匿名slot,父组件内多于的内容片断都将被抛弃。

渲染结果:

<div class="container">
   <div class="header">
       <h2>标题h2>
   div>
   <div class="main">
       <p>正文内容p>
       <p>更多的正文内容p>
   div>
   <div class="footer">
       <div slot="footer">底部信息div>
   div>
div>

你可能感兴趣的:(Vue.js)