Vue Slots
by lollero
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="mainn.js"></script>
</body>
</html>
JavaScript
let headingBoy = {
name: 'headingBoy',
props: ['size', 'text', 'buttons'],
template: `
<div>
<h1 v-if="size === 'large' ">{{ text }}</h1>
<h2 v-else-if="size === 'medium'">{{ text }}</h2>
<h3 v-else-if="size === 'small' ">{{ text }}</h3>
<button v-if="useButtons.save" @click="save">save</button>
<button v-if="useButtons.cancel" @click="cancel">cancel</button>
<button v-if="useButtons.reset" @click="reset">reset</button>
<button v-if="useButtons.world" @click="world">world</button>
</div>
`,
data: function() {
return {
useButtons: {},
};
},
created: function() {
let vue = this;
if ( this.buttons ) {
let buttons = this.buttons.split(',');
buttons.forEach(function( button ) {
vue.useButtons[ button.trim() ] = true;
});
}
},
// I might make the buttons into separate components if they have
// complex logic, structure, or I needed to use them somewhere else too.
methods: {
save: function() {
alert('save');
},
cancel: function() {
alert('cancel');
},
reset: function() {
alert('reset');
},
world: function() {
alert('hello');
},
}
};
var vm = new Vue({
el: '#app',
components: {
headingBoy,
},
template: `
<div>
<heading-boy size="large" buttons="save, cancel" text="Lorem ipsum" />
<heading-boy size="medium" buttons="save, cancel, reset" text="Lipsum" />
<heading-boy size="small" buttons="save, cancel, reset, world" text="Lipsum" />
</div>
`
})