Skip to main content

Accessing CloudBase Data Models in Vue Applications

Learn how to create CloudBase MySQL data models, add sample data, and query data from Vue applications.

1. Create a MySQL Data Model and Add Data

Create a data model named todos in the Cloud Development Platform, with the field information as follows:

Field NameField IdentifierData TypeRequiredUnique
Completion Statusis_completedBooleanNoNo
DescriptiondescriptionText, Multi-line textNoNo
TitletitleText, Single-line textNoNo

After creation, enter sample data in the todos data model.

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 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 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.