Vue
Building an interactive user interface with Vue and Pinia.
Vue allows us to describe how an interface represents application data and how users interact with it. Pinia complements Vue by providing shared reactive state and operations on that state.
In this part, we will explore:
- Vue components and structure
- Reactive state and data binding
- Rendering collections and handling user interactions
- Data modelling, derived state and form submission
- Component props and conditional rendering
- Single-Page App navigation and routing
We will explore these concepts by building a polling application called Poll Box, working entirely in the browser before introducing the backend.
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. Once you have completed this chapter, you will be well prepared for the remaining ones.
Keep the devserver running and the application open in your browser to see the effects of your changes as you save.
1. Understanding Vue components
Open frontend/src/components/HelloWorld.vue. Vue components are typically written in .vue files, known as single-file components. They consist of three sections:
<script setup>what it does (JavaScript or TypeScript)<template>what it shows (HTML)<style scoped>how it looks (CSS)
We can use these sections independently as needed.
Creating a component
Our first task is to provide an input for entering a poll question. Create a new file in the Explorer panel by right-clicking the components folder and choosing New File.... Name it PollForm.vue and enter the following code:
<template>
<section>
<h2>Create a poll</h2>
<label>Question<input type="text"></label>
</section>
</template>
This is already a valid Vue component. We only need ordinary HTML at this point, so there is no script section. Weβll need to use the component in our app to make it actually show up.
Composing the application
Open frontend/src/App.vue. Remove the HelloWorld import, replace the generated header with the following heading and navigation, and place the existing RouterView inside <main>:
<template>
<h1>Poll Box</h1>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/new">New poll</RouterLink>
</nav>
<main>
<RouterView />
</main>
</template>
Keep the RouterLink and RouterView imports. In router/index.ts, import our component alongside HomeView:
import PollForm from '../components/PollForm.vue'
Add a route without changing the generated home route:
{ path: '/new', component: PollForm },
Open New poll to reach the editor at /new. RouterView displays the component for the current route. You may delete the unused HelloWorld.vue.
Styling a component
Add a style section after the template in PollForm.vue:
<style scoped>
section {
display: grid;
gap: 0.75rem;
}
</style>
The scoped attribute limits these rules to this component. The generated base.css also defines colour variables for light and dark mode that we can reuse.
Styling the application
For common styling, 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 existing base.css provides colours that adapt to light and dark mode. Our global stylesheet adds shared layouts and styles for the elements we will use throughout the application.
2. Reactive state and data binding
Type a question into our input. The text currently belongs to the input element itself. What if we also want to display the question as a heading or use it elsewhere in our application?
Rather than reading values from HTML elements and manually updating other elements, we will keep our data in reactive state and bind the interface to it.
Creating a Pinia store
Pinia provides stores for reactive data that can be accessed by multiple components. Our generated project already contains an example store in frontend/src/stores/counter.ts.
Rename the file to polls.ts and examine its contents. We will replace the counter implementation with our own store:
export const usePollsStore = defineStore('polls', {
state: () => ({
question: '',
}),
})
Keep import { defineStore } from 'pinia' at top, but remove the other, now unused import.
The defineStore function defines a store with a unique name, polls, and a state function that returns its initial data. Pinia makes this data reactive. This form of simpler store definition is known as an Options Store, as opposed to the Setup Store syntax used in the counter example.
To access the store from our component, add a script section before the template in PollForm.vue:
<script setup lang="ts">
import { usePollsStore } from '../stores/polls'
const polls = usePollsStore()
</script>
Calling usePollsStore() gives us access to the shared store. Variables declared in <script setup> are directly available in the template. So far, however, nothing in the app itself appears changed.
Connecting the interface to state
Change the heading to display the question from our store:
<h2>{{ polls.question || 'Create a poll' }}</h2>
The double curly braces are Vueβs text interpolation syntax. They evaluate a JavaScript expression and display its result as text. Here we provide a fallback for an empty question.
Connect the input to the same value by adding a v-model directive:
<input type="text" v-model="polls.question">
v-model creates a two-way binding: typing into the input changes the stored value, and changing the stored value 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: Vue automatically updates the parts of the interface that depend on changed data.
3. Dynamic collections and user interactions
A poll can have any number of possible answers. Letβs store them in an initially empty array.
Add a property after question in the state of our store in polls.ts:
options: [] as string[],
The as string[] tells TypeScript that the array will contain strings.
Rendering a collection
We want an input for each answer, plus one empty input for entering another. Vue provides v-for for repeating elements.
Add the following after the question label in PollForm.vue:
<label v-for="n in polls.options.length + 1" :key="n">
Option {{ n }}
<input type="text" v-model="polls.options[n - 1]">
</label>
Here v-for counts from one up to the given number. We subtract one when accessing the array, as array indices start at zero. The key helps Vue keep track of individual elements in the list. The colon before an attribute name tells Vue to evaluate its value as a JavaScript expression rather than use it as literal text.
Try entering an answer. The v-model binding extends the array, and another input appears automatically.
Defining actions
Adding answers works, but clearing the last answer leaves an empty entry in the array. Letβs remove empty entries from the end whenever an answer changes.
Pinia provides actions for defining operations on our state. 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. Keeping this logic in the store makes it independent of the component using it.
Handling input events
To call our action instead of letting v-model update the array directly, replace the option input with:
<input
type="text"
:value="polls.options[n - 1] ?? ''"
@input="polls.updateOption(n - 1, ($event.target as HTMLInputElement).value)"
>
We have separated the two directions of data binding:
:valuedisplays the stored answer, or an empty string if none exists.@inputcalls our action whenever the input changes.
Vue makes the browser event available as $event. We tell TypeScript that its target is an HTML input element to access its value.
Try adding and clearing answers. The number of inputs now grows and shrinks automatically. Empty entries between answers remain in place while editing; we will discard them when creating the poll.
4. From input to application data
So far, our store holds the question and answers we are currently editing. To create multiple polls, we need a separate collection of completed polls.
Defining a data structure
TypeScript allows us to describe the structure of an object using an interface. Add the following above the store definition in polls.ts:
export interface Poll {
question: string
options: string[]
}
We will give each poll a unique identifier and use it as a key in an object. This allows us to access individual polls directly by their ID.
Add an initially empty collection of polls to the state:
polls: {} as Record<string, Poll>,
The Record<string, Poll> type describes an object with string keys and Poll objects as values.
Deriving values from state
Before creating a poll, we need a non-empty question and at least two answers. Rather than maintaining a separate variable indicating whether the form is valid, we can calculate it from the existing state.
Pinia provides getters for this purpose. Add a getters section between state and actions:
getters: {
canCreate: state => Boolean(state.question.trim()) && options.length >= 2,
},
We can access canCreate like any other store property, but its value automatically follows changes to the question and answers.
Creating a poll
Add a createPoll action 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 that the input is valid, stores the poll under a newly generated UUID, discards empty answers and clears the editor.
Submitting a form
We want to create a poll by clicking a button or pressing Enter. HTML forms already provide this behaviour.
In PollForm.vue, wrap the question and option labels in a <form>...</form>, leaving the heading outside it. Use the following opening tag:
<form @submit.prevent="polls.createPoll()">
The @submit event calls our action. The .prevent modifier prevents the browserβs normal form submission.
Paint the lines left inside and press Tab key to maintain correct indentation. Add a button after the option inputs, inside the form:
<button :disabled="!polls.canCreate">Create poll</button>
The button remains disabled until our getter returns true.
Try entering a question and two answers, then submit the form. The editor clears, ready for another poll. Our completed poll is now stored in Pinia, but we have yet to display it.
Notice that little V button at the bottom of your app? Click that and choose Pinia to inspect your store contents. Here you should now see your added poll listed. This function is available in devserver but wonβt appear in production.
5. Displaying polls and voting
We can now create polls. Letβs display them on our home page as a collection of interactive cards.
Recording votes
Our completed polls need to contain both the answer labels and their vote counts.
In polls.ts, define an interface above Poll:
interface Option {
label: string
votes: number
}
Change the type of options in the Poll interface:
options: Option[]
In createPoll, extend the existing processing of options to give each an initial vote count of zero:
options: this.options
.map(option => option.trim())
.filter(Boolean)
.map(label => ({ label, votes: 0 })),
Add another property to the state to keep track of polls we have voted on:
votedPollIds: [] as string[],
Add an action that records a vote, preventing repeated voting on the same poll:
submitVote(id: string, index: number) {
if (this.votedPollIds.includes(id)) return
this.polls[id].options[index].votes++
this.votedPollIds.push(id)
},
Displaying an individual poll
We want a reusable component that receives a poll and displays either its voting buttons or its results.
Create frontend/src/components/PollCard.vue:
<script setup lang="ts">
import { usePollsStore, type Poll } from '../stores/polls'
defineProps<{ id: string, poll: Poll }>()
const polls = usePollsStore()
</script>
<template>
<article>
<h3>{{ poll.question }}</h3>
<div v-if="!polls.votedPollIds.includes(id)" class="stack">
<button
v-for="(option, index) in poll.options"
:key="index"
@click="polls.submitVote(id, index)"
>
{{ option.label }}
</button>
</div>
<ul v-else>
<li v-for="(option, index) in poll.options" :key="index">
{{ option.label }} β {{ option.votes }}
</li>
</ul>
</article>
</template>
Vue calls data passed to a component props. The defineProps declaration describes the values our component expects to receive.
The v-if and v-else directives display alternative content depending on a condition. Once we vote, the buttons are replaced by the results.
Displaying the collection
Our polls are stored by ID, but we want to display them alphabetically by question. Add another getter in polls.ts:
sortedPolls: state =>
Object.entries(state.polls).sort(([, a], [, b]) =>
a.question.localeCompare(b.question),
),
This gives us a sorted array of ID and poll pairs without changing the original collection.
Open the generated HomeView.vue and replace its script imports and store setup with:
import PollCard from '../components/PollCard.vue'
import { usePollsStore } from '../stores/polls'
const polls = usePollsStore()
Replace its template:
<template>
<section>
<h2>Polls</h2>
<p v-if="polls.sortedPolls.length === 0">No polls yet.</p>
<div v-else class="cards">
<PollCard
v-for="[id, poll] in polls.sortedPolls"
:key="id"
:id="id"
:poll="poll"
/>
</div>
</section>
</template>
Here v-for repeats components and passes each poll its corresponding data.
Reload to clear polls using the earlier data structure. Create several polls and return home to see the responsive card grid. Try voting on one.
6. Navigation and routing
We already use Vue Router to navigate between the home page and the poll creation form. Letβs extend this to give each poll its own URL.
Routes with parameters
Rather than defining a separate route for every poll, we can use its ID as part of the URL.
Create frontend/src/views/PollView.vue:
<script setup lang="ts">
import { computed } from 'vue'
import { usePollsStore } from '../stores/polls'
import PollCard from '../components/PollCard.vue'
const props = defineProps<{ id: string }>()
const polls = usePollsStore()
const poll = computed(() =>
Object.hasOwn(polls.polls, props.id) ? polls.polls[props.id] : undefined
)
</script>
<template>
<PollCard v-if="poll" :id="id" :poll="poll" />
<p v-else>Poll not found.</p>
</template>
The computed function works like a Pinia getter, but within a component. Here it retrieves the poll matching the given ID.
In frontend/src/router/index.ts, add an import:
import PollView from '../views/PollView.vue'
Add an entry to the existing routes array:
{ path: '/poll/:id', component: PollView, props: true },
The :id is a variable part of the URL, known as a route parameter. With props: true, Vue Router passes it to the component as a prop.
Linking to individual polls
In PollCard.vue, import RouterLink:
import { RouterLink } from 'vue-router'
Make the question heading a link to the individual poll:
<h3>
<RouterLink :to="`/poll/${id}`">{{ poll.question }}</RouterLink>
</h3>
We can now open any poll on its own page, reusing the same interactive card.
Navigating from code
After creating a poll, we want to return to the home page automatically.
Add a return value at the end of the createPoll action to indicate successful creation:
return true
In PollForm.vue, import useRouter:
import { useRouter } from 'vue-router'
Add the following to the script section:
const router = useRouter()
function submit() {
if (polls.createPoll()) {
router.push('/')
}
}
Change the formβs submission handler to call our function:
<form @submit.prevent="submit">
The routerβs push method allows us to navigate from JavaScript instead of through a link.
Where we are now
We have built an interactive application with reusable components, reactive state and navigation between pages.
However, everything happens within a single browser. Reloading the application loses our data, and we cannot share polls with anyone else.
In the next part, we will introduce FastAPI to make our polls available to multiple users.