Created
March 25, 2019 22:49
-
-
Save TravisMullen/492da6809e5a880d4cfa9827389bbe23 to your computer and use it in GitHub Desktop.
Loading a custom element from NPM into a Vue component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template lang="pug"> | |
.custom-elements | |
// -- use HTML pre-processor for cleaner and less code/whitespace | |
code Hello World | |
br | |
demo-stage( | |
:headline='headline', | |
:color='color' | |
) | |
// -- assume these style classes are part of a greater design system. | |
button( | |
class="button hollow info" | |
@click.prevent='setColor' | |
) Change the color. | |
</template> | |
<script> | |
/** Use custom elements for common components. */ | |
// npm i --save demo-stage | |
import 'demo-stage' | |
export default { | |
name: 'customElements', | |
data () { | |
return { | |
email: '[email protected]', | |
headline: 'DemoStage in Vue.js', | |
colors: [], | |
color: '' | |
} | |
}, | |
computed: { | |
mailto () { | |
return 'mailto:' + this.email | |
} | |
}, | |
/** use async function for cleaner promise chaining/sequencing */ | |
async mounted () { | |
// add `.json` to /src/assets/. | |
this.colors = await import(/* webpackChunkName: "crayola-colors" */ '@/assets/crayola_colors.json') | |
this.setColor() | |
}, | |
methods: { | |
/** small testable functions - ideally pure functions but here we are mutating state directly. */ | |
pickColor () { | |
const hexValues = Object.values(this.colors) | |
return hexValues[Math.floor(Math.random() * hexValues.length)] | |
}, | |
setColor () { | |
this.color = this.pickColor(this.colors) | |
console.log(`color: %c${this.color}`, `color: ${this.color};font-size: 110%;`) | |
} | |
} | |
} | |
</script> | |
<!-- Add "scoped" attribute to limit CSS to this component only --> | |
<style lang="scss" scoped> | |
$some-scss-var-just-because: lime !default; | |
pre, | |
code { | |
font-family: 'Fira Mono', 'PT Mono', 'Anonymous Pro', Monaco, monospace; | |
background-color: #444; | |
color: $some-scss-var-just-because; | |
} | |
small { | |
font-weight: normal; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment