SoFunction
Updated on 2025-04-04

How to use SQLite database for data storage in Vue3 and Vite projects

This article will explain how to use SQLite databases for data storage in Vue3 and Vite projects. We will usebetter-sqlite3Library 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-sqliteNew 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-sqlite3The library created a name calleddbthe SQLite database instance and export it. At the same time, we also defined a name calledinitDbfunction, used to initialize the database. existinitDbIn the function, we use SQL statement to create a namedtodostable, which includesidtextandcompletedThree 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 calledTodoclass, used to represent data model to do things. In the constructor, we definetextandcompletedTwo attributes. At the same time, we also definedsavefindAllfindByIdupdateanddeleteand other methods are used to add, delete, modify and check the data.

existsaveIn the method, we use SQL statements to insert the current to-do item intotodosin the table. existfindAllIn the method, we use SQL statements to query all to-do items and convert the query results toTodoInstance of class. existfindByIdIn the method, we use SQL statements to query the to-do items with the specified ID and convert the query results toTodoInstance of class. existupdateIn the method, we use SQL statements to update the to-do items with the specified ID. existdeleteIn 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 calledTodoListVue component for displaying to-do lists. existdataIn  , we definednewTodoTextandtodosTwo attributes. existmountedIn the life cycle hook, we useTodoClassicfindAllMethod query all to-do items and assign the query results totodosAttributes. In the template, we usev-forInstruction renderingtodosList and passv-modelInstructions and@changeEvents are checked and updated to-do items. At the same time, we also passed@clickThe event has realized the deletion of to-do items.

Integration SQLite

Now, we can useTodoThe class can also perform addition, deletion, modification and search operations on SQLite databases.TodoListComponent 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 usecreateAppFunction creates a Vue application and mounts it to HTML#appon 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-sqlite3Library 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!