【Vue.js 入门到实战教程】09-Vue 组件插槽 | 父子组件间的内容分发和插槽作用域

插槽的作用

命名插槽
<html><head><meta charset="UTF-8"><title>插槽及其作用域使用示例title><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"><script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous">script><script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js">script>head><body><div id="app"><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">模态框button><modal-example><template slot="header">标题template>主体内容...modal-example>div><script>Vue.component('modal-example', {template: '<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">' +' <div class="modal-dialog">' +' <div class="modal-content">' +' <div class="modal-header">' +' <h5 class="modal-title" id="exampleModalLabel"><slot name="header">slot>h5>' +' <button type="button" class="close" data-dismiss="modal" aria-label="Close">' +' <span aria-hidden="true">×span>' +' button>' +' div>' +' <div class="modal-body">' +' <slot>slot>' +' div>' +' <div class="modal-footer">' +' <button type="button" class="btn btn-secondary" data-dismiss="modal">Closebutton>' +' <button type="button" class="btn btn-primary">Save changesbutton>' +' div>' +' div>' +' div>' +'div>'});new Vue({el: '#app'})script>body>html>
<div class="modal-header"><h5 class="modal-title" id="exampleModalLabel"><slot name="header">slot>h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×span>button>div><div class="modal-body"><slot>slot>div>
<modal-example><template slot="header">标题template>主体内容...modal-example>
<slot name="header">slot>

# 视图部分<modal-example><template slot="header">标题template><template slot="body">主体内容...template>modal-example>...# 组件模板<div class="modal-header"><h5 class="modal-title" id="exampleModalLabel"><slot name="header">slot>h5>...div><div class="modal-body"><slot name="body">slot>div>
默认内容
# 视图部分<modal-example>modal-example>...# 组件模板<div class="modal-header"><h5 class="modal-title" id="exampleModalLabel"><slot name="header">默认标题slot>h5>...div><div class="modal-body"><slot name="body">默认内容slot>div>

作用域
# HTML 视图Web 编程语言{{ slotProps.language }}☑️...# 组件模板Vue.component('modal-example', {props: ['languages'],template: ... +'' +' +'' +
'' \n' +' ' +''' +' +'' +
{{ language }} '...});
{{ language }}
{{ slotProps.language }}☑️


评论
