Vue
Building an interactive user interface with Vue and Pinia.
Vue lets us describe how an interface represents application data and responds to user interactions. Pinia complements Vue by providing reactive state that can be shared across components.
In this part, we will explore:
- Single-file components, application structure and styling
- Reactive state and two-way data binding
- List rendering, store actions and event handling
- Data modelling, getters and form submission
- Component props, conditional rendering and computed properties
- Route parameters and programmatic navigation
To explore these concepts, we will build a polling application called Poll Box. For now, everything will run in the browser, allowing us to concentrate on the frontend before introducing the server.
The Vue chapter is the most substantial part of this tutorial, as this is where we implement most of the application. Feel free to take breaks between the sections outlined above and return at your own pace.
Keep the devserver running and the application open in your browser both visible on your screen, such that you can see the effects of your changes as you save. If you have extra display space, try to fit this tutorial on it as well. The less Alt+Tabbing betweewn windows the better.
1. Building an interface with components
Rather than describing an entire interface in one file, Vue allows us to build it from smaller, independent pieces called components. Each component can describe its own appearance and behaviour, and can be used within other components.
Open frontend/src/components/HelloWorld.vue. Vue components are typically written in .vue files, known as single-file components. They can contain three sections:
<script setup>β what it does (JavaScript or TypeScript)<template>β what it shows (HTML with Vue extensions)<style>β how it looks (CSS)
We only need to include the sections that serve a purpose in our component.
1. Building an interface with components
Rather than describing an entire interface in one file, Vue allows us to build it from smaller, independent pieces called components. Each component can describe its own appearance and behaviour, and can be used within other components.
Open frontend/src/components/HelloWorld.vue. Vue components are typically written in .vue files, known as single-file components. They can contain three sections:
<script setup>β what it does (JavaScript or TypeScript)<template>β what it shows (HTML with Vue extensions)<style>β how it looks (CSS)
We only need to include the sections that serve a purpose in our component.
Creating a view
Our generated project organises components into two directories:
views/contains components representing entire pages.components/contains reusable pieces of the interface.
Both use the same single-file component syntax. The distinction is simply a way of organising our application.
Poll Box will have a home page for browsing polls and a separate page for creating them. Letβs start with a simple form for entering a question.
Create frontend/src/views/NewPollView.vue:
<template>
<section>
<h2>Create a poll</h2>
<label>Question<input type="text"></label>
</section>
</template>
This is already a valid Vue component. Ordinary HTML is sufficient for our first version, so we do not need a script or styles yet.
We now need to make this view accessible through navigation.
Connecting routes and views
Our generated application already has two pages, Home and About. Try navigating between them and notice how the URL changes without reloading the application.
This is characteristic of a single-page application: the browser loads the application once, and Vue changes the displayed content as we navigate.
Open frontend/src/router/index.ts. This file configures Vue Router. Its routes array defines which component to display for each URL path.
The home route displays HomeView.vue at /, while the about route displays AboutView.vue at /about.
We donβt need an About page, but we do need a page for creating polls. Adapt the second route to point to our new view:
{
path: '/new',
name: 'new',
component: () => import('../views/NewPollView.vue'),
},
Notice that the generated router imports the home view directly, while the second view is loaded only when its route is visited. This is known as lazy loading, which helps keep the initial application download smaller.
Our new view is now accessible at /new. We still need to update the navigation to take us there.
Composing the application
Open frontend/src/App.vue, the root component of our application.
Here we find two components provided by Vue Router:
RouterLinkprovides links between pages without reloading the application.RouterViewdisplays the component matching the current route.
This arrangement allows us to keep elements such as headings and navigation in place while the page content changes.
We can simplify the generated template to give Poll Box its own heading and navigation. Remove the HelloWorld import, keeping the RouterLink and RouterView imports:
<template>
<h1>Poll Box</h1>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/new">New poll</RouterLink>
</nav>
<main>
<RouterView />
</main>
</template>
Click New poll in your application. Vue Router matches /new to our new route, and RouterView displays the form.
Our application now has a common layout and two independently defined pages. We can develop either view without having to modify the other.
You may delete the unused HelloWorld.vue and AboutView.vue files.
Global and component styling
As our application grows, some styles will belong to individual components, while others should be shared throughout the application.
To give our form a little structure, add a style section after the template in NewPollView.vue:
<style scoped>
section {
display: grid;
gap: 0.75rem;
}
</style>
The scoped attribute limits these rules to this component. Without it, the rules would also apply to matching elements elsewhere in the application.
Common styling, on the other hand, is best kept in a global stylesheet. This gives our inputs, buttons and layouts a consistent appearance without repeating the same rules in every component.
CSS itself is outside the scope of this tutorial. We will prepare the common styles now and introduce component-specific styles as needed.
Remove the generated style section from App.vue and replace frontend/src/assets/main.css with:
@import './base.css';
/* Light and dark appearance */
:root {
color-scheme: light dark;
}
/* Application layout */
#app {
max-width: 1200px;
margin: 0 auto;
padding: 1.5rem;
display: grid;
gap: 1rem;
}
/* Common vertical layouts */
main, section, article, form, .stack {
display: grid;
align-content: start;
gap: 0.75rem;
}
/* Content panels */
main, article {
padding: 1rem;
border: 1px solid var(--color-border);
border-radius: 0.5rem;
background: var(--color-background-soft);
}
/* Responsive card collection */
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
gap: 1rem;
}
/* Navigation */
nav {
display: flex;
gap: 1rem;
}
a {
color: inherit;
}
/* Labelled text inputs */
label:has(input[type="text"]) {
display: grid;
grid-template-columns: 7rem 1fr;
align-items: center;
gap: 0.75rem;
}
/* Form controls */
input[type="text"], button {
font: inherit;
padding: 0.5rem 0.75rem;
border: 1px solid var(--color-border);
border-radius: 0.4rem;
background: var(--color-background);
color: inherit;
}
input[type="text"] {
width: 100%;
min-width: 0;
}
button {
cursor: pointer;
}
button:not(:disabled):hover {
border-color: var(--color-border-hover);
}
button:disabled {
opacity: 0.5;
cursor: default;
}
The generated base.css provides colour variables that adapt to light and dark mode. Our main.css builds upon those with styles shared across the application.
Global and scoped styles can both apply to the same element. The usual CSS rules determine which takes precedence, with scoped selectors generally having greater specificity.
2. Making the interface reactive
We can now type a question into our form, but the text belongs to the input element itself. What if we want to display the question elsewhere, or use it from another component?
Rather than reading values from HTML elements and manually updating other elements, we will keep our data in reactive state and let Vue keep the interface in sync with it.
Pinia to share state
Local variables?
Vue supports reactive state within individual components by ref mechanism. Every instance of the component has these as its local variables where it can store whatever needs storing. They make a good solution for things that truly are local.
We usually prefer to use Pinia, which totally arenβt global variables, but that we can and do access from anywhere in the application.
Pinia provides stores for this purpose. Our generated project already contains an example store in frontend/src/stores/counter.ts.
Click on it and press Enter to rename the file. Give it a new name master.ts and examine its contents. Instead of counting button presses, our store will initially hold the question being edited:
export const useMasterStore = defineStore('master', {
state: () => ({
question: '',
}),
})
Keep import { defineStore } from 'pinia' at the top, removing the other, now unused import.
The defineStore function defines a store with a unique name, master, and a state function that returns its initial data. Pinia makes this data reactive.
This syntax is known as an Options Store, as opposed to the Setup Store used in the generated counter store.
To access the store from our form, add a script section before the template in NewPollView.vue:
<script setup lang="ts">
import { useMasterStore } from '../stores/master'
const master = useMasterStore()
</script>
Calling useMasterStore() gives us access to the shared store. Any other component can access the same store in this way.
Variables declared in <script setup> are directly available in the template. We can therefore start using master in our HTML.
Displaying reactive data
Instead of showing a fixed heading, letβs display the question from our store whenever it is available.
The double curly braces are Vueβs text interpolation syntax. We can place a JavaScript expression between them, and Vue displays its result as text.
Change the heading to:
<h2>{{ master.question || 'Create a poll' }}</h2>
Our expression provides a fallback for an empty question, so the heading still displays βCreate a pollβ.
Two-way data binding
Typing into the input still has no effect on the heading. We have connected the heading to our state, but not the input.
Vue provides the v-model directive for connecting form controls to reactive values. Add it to the question input:
<input type="text" v-model="master.question">
This establishes a two-way binding: typing into the input changes the stored question, and changing the stored question updates the input.
Try entering a question such as βWhere should we meet?β. The heading updates with every keystroke. Clearing the input restores the original heading.
This is reactivity in action. Neither the heading nor the input needs to know about the other. They simply depend on the same reactive value, and Vue updates them whenever that value changes.
3. Working with a bunch of items
A question alone is not much of a poll. We also need possible answers, but we cannot know in advance how many the user will want to enter.
Instead of writing a fixed number of inputs, we can describe how to generate them from a list of answers.
Rendering lists with v-for
Add an initially empty array after question in the state of our store in master.ts:
options: [] as string[],
The as string[] tells TypeScript that this array will contain strings.
We want an input for every answer already entered, followed by one empty input for entering another. Vueβs v-for directive allows us to repeat elements without writing each one individually.
Add the following after the question label in NewPollView.vue:
<label v-for="n in master.options.length + 1" :key="n">
Option {{ n }}
<input type="text" v-model="master.options[n - 1]">
</label>
In this form, v-for counts from one up to the given number like puny humans do. Real coders know that array indices start at zero, so we subtract one when accessing the corresponding answer. We also intentionally show one extra field for adding more options.
The key gives Vue a way to identify each element when the list changes. The colon before the attribute name tells Vue to evaluate its value as a JavaScript expression rather than use it as literal text.
Try entering an answer. The binding extends the array, changing its length. Vue reacts to this change by displaying another input.
Actions on store
Our list of inputs now grows automatically. However, clearing the last answer leaves an empty entry in the array, so the number of inputs never decreases.
We need a little more control over how our state changes.
Pinia allows us to define operations on the store through actions. Instead of directly assigning a new value from the input, we can provide an operation that also removes empty entries from the end of the array.
Add an actions section alongside state in the store definition:
actions: {
updateOption(index: number, value: string) {
this.options[index] = value
while (this.options.at(-1) === '') {
this.options.pop()
}
},
},
Within an action, this refers to the store itself.
By defining this behaviour in the store, we keep the logic for managing our data separate from the interface that uses it.
Hard mode: without bindings
Our input currently uses v-model to read and write an array entry directly. To call our action instead, we need to handle the two directions of data binding separately.
Change the option input to:
<input
type="text"
:value="master.options[n - 1] ?? ''"
@input="master.updateOption(n - 1, ($event.target as HTMLInputElement).value)"
>
The :value binding controls what the input displays. The colon makes it run the code given and use the result in value attribute.
The @ means event handlers. The code runs on input, whenever the user types something. Vue makes the browser event available as $event. We tell TypeScript that its target is an HTML input element to access its value.
We have effectively expressed the two directions of
v-modelseparately, allowing us to introduce our own logic when updating the state.
Try adding and clearing answers. The number of inputs now grows and shrinks automatically. Empty entries between answers remain in place while editing, so the other inputs do not change positions unexpectedly. We will discard those entries when creating the poll.
4. Managing application data
Our form is becoming functional, but so far our state only represents what the user is currently editing.
We want to be able to create a poll, clear the editor and start working on another one without losing the previous poll. This requires us to distinguish temporary form input from the data our application actually manages.
Modelling data with TypeScript
If you donβt like typing in your scripts, feel free to work with JavaScript instead. As may have noticed, Vue allows mixing both and using whatever works.
A completed poll consists of a question and a list of answers. We can describe this structure using a TypeScript interface.
Add the following above the store definition in master.ts:
export interface Poll {
question: string
options: string[]
}
Defining a type lets us use the same description of a poll throughout our application. TypeScript can then help us ensure that different parts of the application use the data consistently.
We also need a way to store and identify multiple polls. Rather than relying on their positions in an array, we will give each poll a unique identifier and use it as a key in a dictionary.
Add another property to the state:
polls: {} as Record<string, Poll>,
The Record<string, Poll> type describes an object with string keys and Poll objects as values.
We can now access individual polls directly by their identifiers, independently of how we choose to display or sort them.
Deriving state with getters
Before creating a poll, we need to determine whether the user has entered enough information.
We could maintain a separate variable indicating whether the form is ready, updating it whenever the question or answers change. But that information can already be determined from our existing state.
Pinia provides getters for values derived from state. Add a getters section between state and actions:
getters: {
canCreate: state => Boolean(state.question.trim()) && state.options.length >= 2,
},
We can access canCreate like any other store property. Unlike an ordinary state property, however, its value is calculated from other values.
Pinia automatically keeps it up to date as the user edits the question and answers.
Turning form input into stored data
We now have a place for completed polls and a way to determine when the editor is ready.
Creating a poll involves several changes to our state: assigning an identifier, storing the question and answers, and clearing the editor. As before, an action lets us express these changes as a single operation.
Add createPoll alongside updateOption:
createPoll() {
if (!this.canCreate) return
this.polls[crypto.randomUUID()] = {
question: this.question.trim(),
options: this.options.map(option => option.trim()).filter(Boolean),
}
this.question = ''
this.options = []
},
The action checks whether the poll can be created, generates a unique identifier using the browserβs UUID generator, and stores the poll with any empty answers removed.
The editor can then be cleared without affecting the completed poll.
Handling form submission
We have defined the operation, but the user still needs a way to trigger it.
HTML forms already support submission through a button or by pressing Enter. We can use this behaviour while letting Vue handle the submission instead of sending the form to a server.
In NewPollView.vue, wrap the question and option labels in a <form>...</form>, leaving the heading outside it. Use the following opening tag:
<form @submit.prevent="master.createPoll()">
The @submit binding listens for the form submission event. The .prevent modifier prevents the browserβs default action, which would otherwise cause navigation or a page reload.
Select the lines inside the form and press Tab to maintain correct indentation.
Add a submission button after the option inputs, inside the form:
<button :disabled="!master.canCreate">Create poll</button>
Here we put our getter to use in the interface. The buttonβs disabled attribute follows the value of canCreate, automatically enabling or disabling the button as the user edits the form.
Try entering a question and two answers, then submit the form. The editor clears, ready for another poll.
Our application now holds completed polls, but we have yet to display them.
Notice the little V button at the bottom of your application? Open it and choose Pinia to inspect the contents of your store. You should now see your newly created poll. These developer tools are available during development but will not appear in production.
5. Building reusable components
Until now, our interface has focused on entering data. We can now approach the problem from the other direction: how do we present the data our application holds?
We want each poll to appear as an interactive card that can be used both on the home page and, later, on a page of its own.
Extending the data model
Before displaying our polls, we need to extend their data model to support voting.
Rather than storing a vote count alongside each answer, we will record which answer each voter has chosen. This allows us to derive the results from the individual votes.
Extend the Poll interface in master.ts with a dictionary of votes:
export interface Poll {
question: string
options: string[]
votes: Record<string, number>
}
Each key identifies a voter, and each value is the zero-based index of their chosen answer. The server will eventually use IP addresses as voter identifiers. In our browser-only version, we use the placeholder key local.
Our createPoll action must now initialise each new poll with an empty dictionary of votes:
this.polls[crypto.randomUUID()] = {
question: this.question.trim(),
options: this.options.map(option => option.trim()).filter(Boolean),
votes: {},
}
The interface also needs to remember which polls the current user has already voted on. Add another property to the storeβs state:
votedPollIds: [] as string[],
We can now define an action that records the userβs choice and marks the poll as voted on:
submitVote(id: string, index: number) {
if (this.votedPollIds.includes(id)) return
this.polls[id].votes.local = index
this.votedPollIds.push(id)
},
With the data and operations in place, we can concentrate on building the voting interface.
Component props and conditional rendering
We could write a component that retrieves a particular poll from the store. But what if we want to display several polls on the same page?
A more flexible approach is to let the component receive the poll it should display. Vue calls values passed into a component props.
Our component will also need to display different content depending on whether the user has already voted. Before voting, it shows the available answers; afterwards, it shows the results.
Create frontend/src/components/PollCard.vue:
<script setup lang="ts">
import { useMasterStore, type Poll } from '../stores/master'
import BarGraph from './BarGraph.vue'
defineProps<{ id: string, poll: Poll }>()
const master = useMasterStore()
</script>
<template>
<article>
<h3>{{ poll.question }}</h3>
<div v-if="!master.votedPollIds.includes(id)" class="stack">
<button
v-for="(option, index) in poll.options"
:key="index"
@click="master.submitVote(id, index)"
>
{{ option }}
</button>
</div>
<BarGraph v-else :poll="poll" />
</article>
</template>
The defineProps declaration describes the values our component expects to receive: a poll identifier and a Poll object. These are directly available in the template.
We use the v-if and v-else directives for conditional rendering. Vue displays one branch or the other depending on whether the user has voted.
Within the first branch, we use v-for to generate a button for every answer. Clicking a button calls our store action, which updates the state. Vue reacts to that change by switching to the results.
For the results, we use another component, BarGraph, passing the poll to it as a prop through :poll="poll".
We have yet to create that component.
Computed properties and dynamic styling
Our data model records individual votes, but a results graph needs the total number of votes for each answer.
As with the formβs validity, we do not need to store these totals separately. They can be calculated from the data we already have.
This time, the calculation belongs to the component displaying the data rather than the shared store. Vue provides computed for defining such reactive values. They will be recomputed when the values used in inner code change.
The graph also needs to change its appearance based on those values. Vue allows us to bind CSS classes and styles to JavaScript expressions just as we bind other attributes.
Create BarGraph.vue component:
Read this component in more detail if interested, or use it as a fancy box that renders colored bars and get along with the tutorial. That after all is how components are supposed to be used.
We will cover only the key concepts below.
<script setup lang="ts">
import { computed } from 'vue'
import type { Poll } from '../stores/master'
const { poll } = defineProps<{ poll: Poll }>()
const counts = computed(() => {
const counts = poll.options.map(() => 0)
for (const index of Object.values(poll.votes)) counts[index]++
return counts
})
const max = computed(() => Math.max(1, ...counts.value))
</script>
<template>
<div v-for="(option, index) in poll.options" :key="index" class="result">
<div
class="bar"
:class="{ winner: counts[index] === max }"
:style="{ width: `${100 * counts[index] / max}%` }"
></div>
<span>{{ option }} Β· {{ counts[index] }}</span>
</div>
</template>
<style scoped>
.result {
display: grid;
font-weight: bold;
}
.result > * {
grid-area: 1 / 1;
}
.bar {
background: linear-gradient(#fff2, #0002), #8885;
border-radius: .4em;
}
.winner {
background-color: #4b68;
}
span {
padding: .5em 1em;
}
</style>
In script blocks we access computed properties and refs through .value rather than by the variable name itself (a JS quirk needed for reactive tracking). Vue handles this automatically within templates, and Pinia does not require it because you are already accessing dotted properties.
The appearance of each bar follows these values:
:classadds thewinnerCSS class when the given condition is true.:styledetermines the width of the bar relative to the highest vote count.
Notice that we can render multiple BarGraphs for diffent polls we wish to show at the same time.
Rendering lists of components
We now have a component that can display any given poll. To display all our polls on the home page, we can use v-for to repeat the component itself.
Our polls are stored in a dictionary, but we want to display them alphabetically by question. Once again, a getter allows us to derive the desired representation without changing the underlying data.
Add another getter in master.ts:
sortedPolls: state =>
Object.entries(state.polls).sort(([, a], [, b]) =>
a.question.localeCompare(b.question),
),
This returns a sorted array of identifier and poll pairs. The original dictionary remains unchanged.
Recall the generated HomeView.vue, which Vue Router displays at /. This is where we want to present our polls.
The view needs access to our store and the component we have created for displaying each poll. Replace its existing script contents with:
import PollCard from '../components/PollCard.vue'
import { useMasterStore } from '../stores/master'
const master = useMasterStore()
For the template, we can reuse the same directives we have already learned. If there are no polls, we display a message. Otherwise, we render a PollCard for each one:
<template>
<section>
<h2>Polls</h2>
<p v-if="master.sortedPolls.length === 0">No polls yet.</p>
<div v-else class="cards">
<PollCard
v-for="[id, poll] in master.sortedPolls"
:key="id"
:id="id"
:poll="poll"
/>
</div>
</section>
</template>
The v-for directive works just as it did with our option inputs, but this time each repeated element is a Vue component.
The key identifies each component instance, while id and poll provide the props declared in PollCard.
Reload the application to clear any polls created before we extended the data model. Create several new polls and return to the home page.
Try voting on one. Its voting buttons are replaced by the results graph, while the other polls remain unchanged.
6. Navigating between views
So far, our routes have had fixed paths. Vue Router also supports route parameters, allowing us to display different data depending on the URL.
Add a route in router/index.ts:
{
path: '/poll/:id',
name: 'poll',
component: () => import('../components/PollCard.vue'),
props: true,
},
With props: true, the :id parameter is passed to PollCard as a prop.
In PollCard.vue, import computed from vue and retrieve the poll by its identifier instead of receiving it as a prop:
const props = defineProps<{ id: string }>()
const master = useMasterStore()
const poll = computed(() => master.polls[props.id])
Add v-if="poll" to the <article> and remove the now unnecessary :poll binding in HomeView.vue.
Finally, import RouterLink in PollCard.vue and make the heading a link:
<h3>
<RouterLink :to="{ name: 'poll', params: { id } }">{{ poll.question }}</RouterLink>
</h3>
Vue Router constructs the URL from the route name and its parameters. Each poll can now be opened on its own page, reusing the very same component.
Vue Router also supports programmatic navigation, allowing us to navigate in response to application logic rather than through links. We could use this, for example, to return to the home page automatically after creating a poll.
Where are we now?
Our application now allows us to create polls, navigate between them, vote and view the results. Vue keeps the interface in sync with our data, while Pinia provides a common place to manage that data.
However, everything happens within a single browser. Reloading the application loses our data, and sharing a pollβs URL with someone else does not give them access to the poll.
For a polling application to be useful, its data must be shared between users. In the next part, we will introduce FastAPI and connect our existing frontend to a server.