Accessing CloudBase MySQL Databases in Vue Applications
Learn how to create CloudBase MySQL data tables, add sample data, and query data from Vue applications.
1. Create a MySQL Data Table and Add Data
Create a data table named todos in the Cloud Development Platform, with the field information as follows:
| Column Name | Description | Type | Required | Unique |
|---|---|---|---|---|
| id | Identifier | int | Yes | Yes |
| is_completed | Completion Status | boolean | No | No |
| description | Description | text | No | No |
| title | Title | varchar | No | No |
After creation, enter sample data in the todos data table.
2. Create a Vue Application
Requires Node.js version >= 20.19
npm create vite@latest todo -- --template vue
3. Install Cloud Development SDK Dependencies
Execute the following command in the project root directory:
cd todo && npm install @cloudbase/js-sdk
4. Declare Cloud Development Environment Variables
Create the .env.local file and fill in the Cloud Development Environment ID.
VITE_CLOUDBASE_ENV_ID=<CloudBase Environment ID>
5. Querying Data from the Application
In App.vue, add the following code 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.mysql();
}
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 obtain todo items:", error);
}
};
onMounted(() => {
fetchTodos();
});
</script>
<template>
<div>
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.title }}</li>
</ul>
</div>
</template>
6. Launch Application
Execute the following command in the project root directory to launch the application:
npm run dev
Notes
- When operating on different environment data, you must set the corresponding
envType. - If using other login methods (refer to Authentication), replace
auth.signInAnonymously()with the corresponding login method.