LiveView for Real-Time UI Updates
LiveView creates a reactive connection so that your UI updates automatically when data changes on the server. Below is an example of how to integrate LiveView in a Vue project:
vue
<template>
<div class="ormbridge-test">
<h1>ORMBridge Vue Test</h1>
<div class="controls">
<button id="add-item" @click="addItem" :disabled="isLoading || !liveQuery">Add Item</button>
<button id="update-items" @click="updateAllItems" :disabled="isLoading || !liveQuery">Update All</button>
<button id="delete-items" @click="deleteAllItems" :disabled="isLoading || !liveQuery">Delete All</button>
</div>
<div class="items-container">
<h2>Items: <span id="item-count">{{ items.length }}</span></h2>
<p v-if="isLoading">Loading...</p>
<ul v-else id="items-list">
<li v-for="item in items" :key="item.id" class="item" :data-id="item.id">
<strong>{{ item.name }}</strong>: {{ item.value }}
</li>
</ul>
</div>
</div>
</template>
<script>
import { defineComponent, ref, shallowRef } from 'vue';
import { createVueLiveView } from '@ormbridge/core';
import { DummyModel } from '../../models/backend1';
export default defineComponent({
name: 'ORMBridgeTest',
setup() {
const items = ref([]);
const liveQuery = shallowRef(null);
const isLoading = ref(true);
// Initialize LiveView and bind it to the items array
createVueLiveView(DummyModel.objects.all(), items)
.then(query => {
liveQuery.value = query;
isLoading.value = false;
})
.catch(error => {
console.error("Failed to initialize query:", error);
isLoading.value = false;
});
const addItem = async () => {
if (liveQuery.value) {
await liveQuery.value.create({ name: 'New Item', value: Math.floor(Math.random() * 100) });
}
};
const updateAllItems = async () => {
if (liveQuery.value) {
await liveQuery.value.update({ name: 'Updated Item' });
}
};
const deleteAllItems = async () => {
if (liveQuery.value) {
await liveQuery.value.delete();
}
};
return {
items,
liveQuery,
isLoading,
addItem,
updateAllItems,
deleteAllItems
};
},
beforeUnmount() {
if (this.liveQuery) {
this.liveQuery.destroy();
}
}
});
</script>
<style scoped>
.ormbridge-test {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.controls {
margin-bottom: 20px;
}
button {
margin-right: 10px;
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.items-container {
border: 1px solid #ddd;
padding: 15px;
border-radius: 4px;
}
.item {
padding: 10px;
margin-bottom: 5px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
}
</style>
This example shows how to initialize a LiveView query with createVueLiveView
, bind the live data to a local reactive array (items
), and provide actions to create, update, or delete items in real time.