Webcomponents y Polymer 2. Ejemplos. Parte 3
Componentes nativos
Para realizar este ejemplo no es necesaria ninguna librería ni framework ya que se usa HTML, CSS y Javascript.
<!DOCTYPE html>
<html lang="es">
<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">
<title>Componentes nativos</title>
<style>
h3 {
color: #00ff00;
}
li {
color: #0000ff;
}
</style>
</head>
<body>
<!-- Inicio del contenido de la página -->
<h3>Fuera componente</h3>
<ul>
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
</ul>
<!-- Uso del componente -->
<componente-basico></componente-basico>
<!-- Definición del template para el componente -->
<template id="listado">
<!-- Estilos dentro del componente -->
<style>
ul {
list-style: none;
margin: 0;
padding: 0;
}
li {
color: #ff00ff;
font-weight: bold;
}
</style>
<!-- HTML dentro del componente -->
<h3>Listado</h3>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
</template>
<script>
// Clase para implementar el componente
class ComponenteBasico extends HTMLElement {
constructor() {
// Siempre debe llamarse primero al constructor padre
super();
// Guardamos el template
let listado = document.getElementById("listado");
// Adjunta un árbol del Shadow DOM al elemento especificado y devuelve una referencia a su ShadowRoot
this.attachShadow({ mode: 'open' }).innerHTML = listado.innerHTML;
}
}
// Asociar la clase al nombre del componente
customElements.define("componente-basico", ComponenteBasico);
</script>
</body>
</html>
Para que todo sea muy simple, he creado todo el código en un único fichero para entender todas las partes del componente.
Componentes con Polymer 2
Vamos a crear dos ficheros. El primer fichero sera una página simple donde importaremos el componente y el segundo fichero sera el componente:
index.html
<!DOCTYPE html>
<html lang="es">
<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">
<title>Polymer 2</title>
<link rel="import" href="./componente-basico/componente-basico.html">
</head>
<body>
<componente-basico></componente-basico>
</body>
</html>
componente-basico.html
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<dom-module id="componente-basico">
<template>
<style>
:host {
display: block;
margin: 15px;
}
h1 {
color: #ff0000;
}
</style>
<h1>
Componente básico
</h1>
</template>
<script>
class ComponenteBasico extends Polymer.Element {
static get is() {
return 'componente-basico';
}
}
window.customElements.define(ComponenteBasico.is, ComponenteBasico);
</script>
</dom-module>
