This article will explain how to use SQLite databases for data storage in Vue3 and Vite projects. We will usebetter-sqlite3
Library to create and manage SQLite databases and will use Vue3 to develop front-end interfaces.
Create a project
first,We need to create a new one Vue3 project。 You can use the following command to create a namedvue-sqlite
New projects:
vue create vue-sqlite
Then, install the required dependencies, includingbetter-sqlite3
:
npm install better-sqlite3
Create a SQLite database
Next, we need to create the SQLite database. You can create a name called "in the root directory of the projectfile and add the following code to the file:
const sqlite = require('better-sqlite3') const path = require('path') const dbPath = (__dirname, '') const db = new sqlite(dbPath) const initDb = () => { (` CREATE TABLE IF NOT EXISTS todos ( id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL, completed INTEGER NOT NULL DEFAULT 0 ); `).run() } = { db, initDb, }
In the above code, we usebetter-sqlite3
The library created a name calleddb
the SQLite database instance and export it. At the same time, we also defined a name calledinitDb
function, used to initialize the database. existinitDb
In the function, we use SQL statement to create a namedtodos
table, which includesid
、text
andcompleted
Three fields.
Create a data model
Next, we need to create a data model. You can create a name called "in the root directory of the projectfile and add the following code to the file:
const { db } = require('./database') class Todo { constructor(text, completed = false) { = text = completed } save() { const stmt = (` INSERT INTO todos (text, completed) VALUES (?, ?) `) (, ? 1 : 0) } static findAll() { const stmt = (` SELECT * FROM todos `) const rows = () return (row => new Todo(, )) } static findById(id) { const stmt = (` SELECT * FROM todos WHERE id = ? `) const row = (id) return row ? new Todo(, ) : null } update() { const stmt = (` UPDATE todos SET text = ?, completed = ? WHERE id = ? `) (, ? 1 : 0, ) } delete() { const stmt = (` DELETE FROM todos WHERE id = ? `) () } } = Todo
In the above code, we define a name calledTodo
class, used to represent data model to do things. In the constructor, we definetext
andcompleted
Two attributes. At the same time, we also definedsave
、findAll
、findById
、update
anddelete
and other methods are used to add, delete, modify and check the data.
existsave
In the method, we use SQL statements to insert the current to-do item intotodos
in the table. existfindAll
In the method, we use SQL statements to query all to-do items and convert the query results toTodo
Instance of class. existfindById
In the method, we use SQL statements to query the to-do items with the specified ID and convert the query results toTodo
Instance of class. existupdate
In the method, we use SQL statements to update the to-do items with the specified ID. existdelete
In the method, we use SQL statements to delete the to-do items with the specified ID.
Create an interface
Next, we need to create the interface. You can create a name called "in the root directory of the projectfile and add the following code to the file:
<template> <div> <h1>Todo List</h1> <form @="addTodo"> <input v-model="newTodoText" type="text" placeholder="Add a new todo"> <button type="submit">Add</button> </form> <ul> <li v-for="todo in todos" :key=""> <input type="checkbox" v-model="" @change="updateTodo(todo)"> <span :class="{ completed: }">{{ }}</span> <button @click="deleteTodo(todo)">Delete</button> </li> </ul> </div> </template> <script> import Todo from './Todo' export default { data() { return { newTodoText: '', todos: [], } }, async mounted() { const rows = await () = rows }, methods: { async addTodo() { const todo = new Todo() () (todo) = '' }, async updateTodo(todo) { () }, async deleteTodo(todo) { () = (t => !== ) }, }, } </script> <style> .completed { text-decoration: line-through; } </style>
In the above code, we define a name calledTodoList
Vue component for displaying to-do lists. existdata
In , we definednewTodoText
andtodos
Two attributes. existmounted
In the life cycle hook, we useTodo
ClassicfindAll
Method query all to-do items and assign the query results totodos
Attributes. In the template, we usev-for
Instruction renderingtodos
List and passv-model
Instructions and@change
Events are checked and updated to-do items. At the same time, we also passed@click
The event has realized the deletion of to-do items.
Integration SQLite
Now, we can useTodo
The class can also perform addition, deletion, modification and search operations on SQLite databases.TodoList
Component displays a to-do list. Next, we need to integrate them. Can be insrc/
Add the following code to the file:
import { createApp } from 'vue' import App from './' import { initDb } from './database' initDb() createApp(App).mount('#app')
In the above code, we first callinitDb()
Function, used to initialize SQLite database. Then, we usecreateApp
Function creates a Vue application and mounts it to HTML#app
on the element.
Now, we have completed the process of creating a SQLite database and storing data using Vue3 and Vite. The application can be started by running the following command:
npm run dev
Open the browser and accesshttp://localhost:3000
, you can see the to-do list page. Now we can add, update, and delete to-do items, and their data is stored in the SQLite database.
Conclusion
This article describes how to use SQLite databases for data storage in Vue3 and Vite projects. We usedbetter-sqlite3
Library to create and manage SQLite databases and use Vue3 to develop front-end interfaces. With the guidance in this article, you can easily integrate SQLite databases into your
This is the article about how to use SQLite databases for data storage in Vue3 and Vite projects. For more related content on Vue3 Vite to use SQLite data storage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!