Slot used in Vue
Case: part of the content in the child component is displayed according to the DOM passed from the parent component
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue Slot used in(slot)</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <child content='<p>Dell</p>'></child> </div> <script> Vue.component('child',{ props:['content'], template:'<div><p>hello</p><div v-html="this.content"></div></div>' }) var vm = new Vue({ el:'#root', }) </script> </body> </html>
Output:
There are problems: 1. If you want to use the < p > in content directly, you must wrap a layer of DIV outside;
2. When passing values to subcomponents in this way, too many values will cause poor code readability
Part of the content in the child component is that when it is displayed according to the DOM passed by the parent component, the slot method can be used
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue Slot used in(slot)</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <child> <p>Dell</p> </child> </div> <script> Vue.component('child',{ props:['content'], //Get slot content template:'<div> <p>Hello</p><slot></slot></div>' }) var vm = new Vue({ el:'#root', }) </script> </body> </html>
Output:
slot can also set the default style
<body> <div id="root"> <child> </child> </div> <script> Vue.component('child',{ props:['content'], //Get slot content template:'<div> <p>Hello</p><slot>Default content</slot></div>' })
Output:
Function: output, in which the header part and the footer part are passed in by the parent component
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue Slot used in(slot)</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <body-content> <div class="header" slot='header'>header</div> <div class="footer" slot='footer'>footer</div> </body-content> </div> <script> Vue.component('body-content',{ //Get slot content template:'<div> <slot name='header'></slot> <div class='content'>content</div> <slot name='footer'></slot> </div>' }) var vm = new Vue({ el:'#root', }) </script> </body> </html>
Giving each slot a specific name is called named slot (there can be multiple or default values, but only one slot)
Output:
Named slot default
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue Slot used in(slot)</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <body-content> <div class="footer" slot='footer'>footer</div> </body-content> </div> <script> Vue.component('body-content',{ //Get slot content template:'<div> <slot name='header'>default header</slot> <div class='content'>content</div> <slot name='footer'></slot> </div>' }) var vm = new Vue({ el:'#root', }) </script> </body> </html>
Output: