Accessing CloudBase MySQL Cloud Database in Vue Applications
Learn how to create a CloudBase MySQL data model, add sample data, and query data from a Vue application.
1. Create MySQL Data Model and Add Data
Create a data model named todos
in the Cloud Development Console with the following field information:
Field Name | Field ID | Data Type | Required | Unique |
---|---|---|---|---|
Is Completed | is_completed | Boolean | No | No |
Description | description | Text, Multiline Text | No | No |
Title | title | Text, Single Line Text | No | No |
After creation, enter sample data in the todos
data model.
2. Create 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 CloudBase Environment Variables
Create a .env.local
file and fill in your 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 cachedApp = null;
const getModels = async () => {
if (!cachedApp) {
cachedApp = cloudbase.init({
env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
});
const auth = cachedApp.auth({
persistence: "local",
});
await auth.signInAnonymously();
}
return cachedApp.models;
};
const todos = ref([]);
const fetchTodos = async () => {
try {
const models = await getModels();
const { data } = await models.todos.list({
filter: { where: {} },
pageSize: 10,
pageNumber: 1,
getCount: true,
envType: "pre",
});
todos.value = data.records;
} catch (error) {
console.error("Failed to get 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
Execute the following command in the project root directory to start the application:
npm run dev
Notes
- When operating on data from different environments, you need to set the corresponding
envType
. - If using other login methods (refer to Authentication), replace
auth.signInAnonymously()
with the corresponding login method.