DEV Community

artydev
artydev

Posted on

Using Web Components with VanJS and Shoelace

It's very straightforward to use web components with VanJS.
Here we use the excellent web component library Shoelace

Demo

import van from "./van.js"

const {
    div,
    h2,
    br,
    img,
    strong,
    small,
    hr,
    "sl-rating": SlRating,
    "sl-button": SlButton,
    "sl-card": SlCard,
  "sl-input": SlInput
} = van.tags

const target = document.getElementById("app");

function GroupButtons(){

    const variant = van.state("...");

    const handleClick = e => variant.val = (e.target.getAttribute("variant"));

    const view = div(
        h2("Buttons : ", variant),
        div(
            SlButton({
                variant: "default"
            }, "one"),
            SlButton({
                variant: "primary"
            }, "two"),
            SlButton({
                variant: "danger"
            }, "three")
        ),
    )
    view.onclick = handleClick;
    return view;
}

function Card(){
    return SlCard({
            class: "card-overview"
        },

        img({
            slot: "image",
            src: "https://images.unsplash.com/photo-1559209172-0ff8f6d49ff7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=80",
            alt: "A kitten sits patiently between a terracotta pot and decorative grasses."
        }),
        strong("Mitten"), br(),
        "This kitten is as cute as he is playful. Bring him home today!", br(),
        small("6 weeks old"),

        div({
                slot: "footer"
            },
            SlButton({
                variant: "primary",
                pill: ""
            }, "More Info   "),
            SlRating()
        )
    )
}

function Input(){
  const value = van.state("input text...")
  const dom =  div(
    div(value),
    br(),
    SlInput({placeholder:"Enter text"})
  )
  const input = dom.querySelector("sl-input")
  input.oninput = () => value.val = input.value
  return dom
}

van.add(
  target, 
  GroupButtons(), br(),
  h2("Card"),
  Card(), br(),
  h2("Input"),
  Input(), br()
)

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
tao_xin_23db52b1401921dcb profile image
Tao Xin (vanjs.org)

nit: do you want to remove the blank line after function GroupButtons() {?

Collapse
 
artydev profile image
artydev

Done :-)