Skip to main content

Access CloudBase PostgreSQL Database from a Vue Application

Learn how to create a CloudBase PostgreSQL data table, add sample data, and query data from a Vue application.

1. Create a PostgreSQL Data Table and Add Data

Create a data table named todos on the Cloud Development platform with the following fields:

Column NameDescriptionTypeRequiredUnique
idIdentifierintYesYes
is_completedCompletedbooleanNoNo
descriptionDescriptiontextNoNo
titleTitlevarcharNoNo

After creation, enter sample data into the todos data table.

2. Create a Vue Application

Requires Node.js version >= 20.19

npm create vite@latest todo -- --template vue

3. Install CloudBase SDK Dependencies

In the project root directory, run the following command:

cd todo && npm install @cloudbase/js-sdk

4. Declare CloudBase Environment Variables

Create a .env.local file and enter the CloudBase environment ID:

VITE_CLOUDBASE_ENV_ID=<CloudBase Environment ID>

5. Query Data from the Application

Add the following code in App.vue to query data:

<script setup>
import { ref, onMounted } from "vue";
import cloudbase from "@cloudbase/js-sdk";

let db = null;

const getDB = async () => {
if (!db) {
const app = cloudbase.init({
env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
});
const auth = app.auth({
persistence: "local",
});
await auth.signInAnonymously();
db = app.rdb();
}
return db;
};

const todos = ref([]);

const fetchTodos = async () => {
try {
const { data } = await getDB().from("todos").select("*").range(0, 9);
todos.value = data;
} catch (error) {
console.error("Failed to fetch todos:", error);
}
};

onMounted(() => {
fetchTodos();
});
</script>

<template>
<div>
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.title }}</li>
</ul>
</div>
</template>

6. Start the Application

In the project root directory, run the following command to start the application:

npm run dev

Notes

  • When operating on data in different environments, set the corresponding envType.
  • If using other login methods (refer to Authentication), replace auth.signInAnonymously() with the corresponding login method.