You will notice that the ArrayList class has an items property that is an array type. Lit won’t let you do something like <array-list items = ['Item 1', 'Item 2', 'Item 3']></array-list> but it is fine with you passing it in using javascript. That means that myList.items = ['Item 1', 'Item 2', 'Item 3']; does the job, fine.
@ewen Un résumé propre 👍
Juste dans le tableau comparatif final, je ne comprends pas pourquoi HTMX est opposé à une SPA (mise du côté de Vue)
Il me semble qu'on peut tout à fait faire une SPA en HTMX. Un menu fait des appels HTMX qui remplacent le <main> entier et voilà
Working with #django and #vuejs I'm using custom tokens so that VueJS and Django tokens don't conflict, but I also have a need to escape to ensure users can't get my VueJS delimiters anywhere.
Is there a place I can hook in to add my own, additional escape code 🤔, or am I doomed to have to add {{value|myescape}} everywhere a value is used 😢
@bmispelon Thanks! Might not be, but gives me something to check. My challenge is that if I have user submittable data (like a ModelForm) and somewhere In a template I use {{ instance.some_field }}, even a failed model submission populates a copy of instance.some_field with the value that can sometimes result in a VueJS directive being placed in unexpected places. (Hard to explain in a post so I might write up a blog post as part of my research)
@kfdm If you do write up something please let me know, it sounds like an intriguing problem (for one thing, I would not expect a modelform with failed validation to change anything on its instance, but I might very much be wrong)
Earlier this week, when I wrote about how to build an autocomplete using Vue.js, it was less about exploring how to do it and more about documenting recent work that used Vuetify. I wanted to use today’s post to go in the other direction. Recently, I discovered the value of using Lit when writing Web Components. I wanted to see if we could go from the HTML / CSS example to a proper web component.
First crack at it
Lit is powerful. You can do a lot with it. Let’s start with a rewrite of Tuesday’s final example to one that uses just Lit.
The first thing that we do in this is to import LitElement, html, css from a CDN. Our CountySelector class extends LitElement and then customElements.define('county-selector', CountySelector) at the bottom of the page is what turns our class into a tag. The static styles definition is how you style the tag. You will notice that there aren’t any styles outside of that. The markup is all defined in render() near the bottom. The async fetchCounties() method gets the list of counties from the data.jws.app site that I created last week.
This works but web components are supposed to be reusable and this isn’t reusable enough, though.
You will notice that the big difference between this version and the first one is that we dropped the API call and replaced it with a countyList property that defines the options. We can do better, though.
In this next version, we eliminate all explicit references to counties since a person might presumably want to use the component for something other than counties. You might want to use it to prompt a user for ice cream flavors or pizza toppings.
How do you use Vue with a web component?
Unfortunately, you aren’t going to be able to use something like v-model with a web component. There are other ways to bind to form inputs, though. Let’s take a look.
In the above example, optionsList and selectedOption are defined as Refs. The ref object is mutable (you can assign new values to .value) and it is reactive (any read operations to .value are tracked, and write operations will trigger associated effects). The options list can be passed into the web component using the :optionsList property. You might notice, though that the example is using .join(', ') to convert the array to a comma-delimited list. That is because you can not pass an array directly into a web component. That is likely going to be the subject of a future article. You might also notice that it is triggering the when you click on a suggestion and onBlur. The dispatchEvent() method sends an event to the object, invoking the affected event listeners in the appropriate order. That should trigger updateSelectedOption when you select a county or finish typing one that isn’t in the list.
So, what do you think? Do you have any questions? Feel free to drop a comment, below.
Have you ever stumbled upon those form fields that suggest options in a drop-down as you type, like when you’re entering a street address? It turns out, that making those are not as difficult as you would think! Today, I’m gonna walk you through three cool ways to pull it off using Vue.js. Let’s dive in!
Vuetify
If you are a Vue developer, you have likely used Vuetify at some point. It is an open-source UI library that offers Vue Components for all sorts of things. One of those things just happens to be Autocompletes.
Last week, I spoke about creating a repository of data for coding examples. The first one is a list of counties in the state of Wisconsin. In this example, the values from the API are stored in a counties array, the value that you entered into the input is stored in a selectedCounty variable, and the fetchCounties method fetches the values from the API. Thanks to the v-autocomplete component, it is super easy using Vuetify.
Shoelace
Shoelace (now known as Web Awesome) doesn’t have a built-in autocomplete element but there is a stretch goal on their kickstarter to add one. That means that we need to build the functionality ourselves.
Our Shoelace version has a filteredCounties variable so that we can control what is shown in the suggestions and a selectCounty method to let the user click on one of the suggestions.
Plain HTML and CSS
We have already established that Shoelace doesn’t have an autocomplete but neither does Bulma or Bootstrap. So, I figured that we would try a pure HTML and CSS autocomplete.
This is very similar to our Shoelace example but with some extra CSS on the input. You might be wondering about that autocomplete attribute on the input. It is a different type of autocomplete. The autocomplete attribute specifies if browsers should try to predict the value of an input field or not. You still need to roll your own for the suggestions.
I have been spending a lot of the past month working on a Vue / Firebase side project, so this is going to be a fairly short post. I recently discovered that there are modifiers for v-model in Vue. I wanted to take a moment to cover what they do.
.lazy
Instead of the change being reflected the moment you make it, this modifier makes it so that the change syncs after change events.
VitePress is a Static Site Generator (SSG) that takes #Markdown, applies a theme to it, and generates static HTML pages. Built on #Vue. #JavaScript#VueJS
The useEffect React hook lets you perform side effects in functional components, such as fetching data, subscribing to a service, or manually changing the DOM. It can be configured to run after every render or only when certain values change, by specifying dependencies in its second argument array. The useMemo React hook memoizes expensive calculations in your component, preventing them from being recomputed on every render unless specified dependencies change. This optimization technique can significantly improve performance in resource-intensive applications by caching computed values.
Let’s walk through what we have going on here. The App() function is returning JSX containing <p>The current time is {currentTime}</p> and currentTime is defined by setCurrentTime. The code block useEffect(() => {}); executes whenever the state changes and can be used to do something like fetching data or talking to an authentication service. It also fires when the page first renders. So, what does that empty dependency array (,[]) do in useEffect(() => {},[]);? It makes sure that useEffect only runs one time instead of running whenever the state changes.
In this example, it still runs useEffect(() => {},[]); only once (instead of whenever the state changes) but it uses setInterval() inside of useEffect to refresh the state once every 1000 milliseconds.
In this one, we have three form elements: a number picker for “digits of pi”, a color picker for changing the background, and a read-only textarea field that shows the value of π to the precision specified in the “digits of pi” input. With no dependency array on useEffect(() => {});, whenever either “Digits of Pi” or the color picker change, useEffect is triggered. If you open the console and make a change, you can see how it is triggered once when you change the background color and twice when you change the digits of pi. Why? It does that because when you change the number of digits, it also changes the value of pi and you get one execution per state change.
In this revision, instead of piValue having a state, it is “memoized” and the value of the variable only changes if the value of digits changes. In this version, we are also adding a dependency array to useEffect() so that it only executes if the value of color changes. Alternatively, you could also just have two . Let’s take a look at that.
If you throw open your console and change the two input values, you will see that it is no longer triggering useEffect() twice when changing the number of digits.
Have any questions, comments, etc? Feel free to drop a comment, below.
The actual blog post is on a WordPress blog and it is publishing to the Fediverse from there. There is some sort of magic that that (first-party) wordpress plugin is doing, but I couldn’t tell you what it is.
Over the years, we have looked at jQuery, AngularJS, Rivets, and Vue.js. I figured that it was time to add React to the list. Facebook developed React for building user interfaces. The big difference between Vue and React is that React uses one-way binding whereas Vue uses two-way binding. With React, data flows downward from parent components to child components and to communicate data back up to the parent component, you would need to use a state management library like Redux. React is also a library where Vue.js is a framework, so React is closer to Rivets. You can run React with or without JSX and write it with or without a framework like Next.js.
Let’s look at how binding works in React and how it compares to Vue. In Vue, if we wanted to bind a form input to a text value, it would look like this …
You will notice that the React version uses the useState React Hook. Where the Vue version uses const inputText = ref('Blah Blah Blah'); for reactive state management, React uses const [inputText, setInputText] = React.useState('Blah Blah Blah'); to manage state. Also, Vue has two-way binding with the v-model directive but with React, the text updates when the state changes, but the state doesn’t automatically update when the input is edited. To deal with this, you manually handle updates to the input’s value via an onChange event. The developer is responsible for triggering state changes using the state updater functions in React. Another big difference is that Vue uses a template syntax that is closer to HTML while with React, JSX is used to define the component’s markup directly within JavaScript.
This example is very similar to what we had before but now there are child elements for setInputText(event.target.value)} /> and <TextDisplay text={inputText} />. This approach promotes code reusability. By encapsulating the input field and display logic into separate components, these pieces can easily be reused throughout the application or even in different projects, reducing duplication and fostering consistency. It is kind of the React way. Each component is responsible for its own functionality — InputForm manages the user input while TextDisplay is solely concerned with presenting text. This separation of concerns makes the codebase easier to navigate, understand, and debug as the application grows in complexity.
Have a question, comment, etc? Feel free to drop a comment.