我们要部署静态网站,因此,需要提前准备按量计费环境。
使用 CloudBase Framework 创建一个 vue 应用。具体操作,参见:如何用 Cloudbase Framework 部署一个 Vue 项目?
{
"envId": "your envId",
"framework": {
"plugins": {
"client": {
"use": "@cloudbase/framework-plugin-website",
"inputs": {
"buildCommand": "npm run build",
"outputPath": "dist",
"cloudPath": "/watch-todolist"
}
},
"database": {
"use": "@cloudbase/framework-plugin-database",
"inputs": {
"collections": [
{
"collectionName": "watch-todos"
}
]
}
}
}
}
}请注意 database 部分的配置。
这里,"database"是自定义的名称,你可以配置成任何你喜欢的名字~
之后,在 package.json 中,相应配置部署的 script 脚本即可。
比如,我们这里配置了:
{
"scripts": {
"deploy:database": "cloudbase framework:deploy database"
}
}配置完成后,执行:
yarn deploy:database
npm run deploy:database
yarn add tcb-js-sdk
npm install tcb-js-sdk
【注】 获取数据库实例,必须先进行登录授权,否则无法获取。
具体实现方式如下:
【step1】云开发控制台开启匿名登录:
import tcb from 'tcb-js-sdk';
import $config from '../../cloudbaserc';
// 初始化
const app = tcb.init({
env: $config.envId,
});
const auth = app.auth();
let db = null;
async function login() {
await auth.signInAnonymously();
// 匿名登录成功检测登录状态isAnonymous字段为true
const loginState = await auth.getLoginState();
console.log(loginState.isAnonymousAuth); // true
return app.database();
}
function getDB() {
if (!db) {
db = login();
}
return db;
}
export default getDB;
import $getDB from './index';
// 正确数据
const data = {
code: 0,
data: null,
msg: 'success',
};
// 操作失败数据
function getFailData(msg) {
return {
code: -1000,
data: null,
msg,
};
}
// 发生错误数据
function getErrorData(err) {
return {
code: -4000,
data: null,
msg: err.message,
};
}
// 数据库集合获取
async function getCollection() {
const db = await $getDB();
return db.collection('watch-todos');
}
// 增加
async function addItem(params) {
const addRes = Object.assign({}, data);
try {
const myCollection = await getCollection();
const res = await myCollection.add(params);
// 如果插入出错
if (!res.id) {
return getFailData('add fail');
}
} catch (e) {
return getErrorData(e);
}
return addRes;
}
// 删除
async function deleteItem({ _id }) {
const deleteRes = Object.assign({}, data);
try {
const myCollection = await getCollection();
const res = await myCollection.doc(_id).remove();
// 如果没有成功删除
if (res.deleted === 0) {
return getFailData('delete fail');
}
} catch (e) {
return getErrorData(e);
}
return deleteRes;
}
// 修改
async function updateItem(params) {
const updateRes = Object.assign({}, data);
const { _id, checked, color, starred, text } = params;
try {
const myCollection = await getCollection();
const res = await myCollection.doc(_id).update({
checked,
color,
starred,
text,
});
// 如果没有成功更新
if (res.updated === 0) {
return getFailData('update fail');
}
} catch (e) {
return getErrorData(e);
}
return updateRes;
}
// 查询
async function getList() {
const listRes = Object.assign({}, data);
try {
const myCollection = await getCollection();
const dbData = await myCollection.get();
listRes.data = {
page: 1,
limit: 10,
total: 100,
list: dbData.data,
};
} catch (e) {
return getErrorData(e);
}
return listRes;
}
export default {
addItem,
deleteItem,
updateItem,
getList,
};
这是 demo 中的 App.vue
import $getDB from './tcb';
import $service from './tcb/service';
methods: {
// 拉取数据列表
async getList() {
const res = await $service.getList();
if (res && res.code === 0) {
this.todoList = [...res.data.list];
}
},
// 注册数据库变动的实时监听
async registerTcbWatcher() {
const getList = this.getList;
const db = await $getDB();
this.watcher = db
.collection('watch-todos')
.where({
// query...
})
.watch({
onChange(snapshot) {
console.log('snapshot', snapshot);
getList();
},
onError(err) {
console.error('the watch closed because of error', err);
},
});
},
},
created() {
this.registerTcbWatcher();
},
destroyed() {
// 关闭数据库变动的实时监听
this.watcher.close();
},
yarn dev
npm run dev
{
"envId": "your envId",
"framework": {
"name": "vue",
"plugins": {
"client": {
"use": "@cloudbase/framework-plugin-website",
"inputs": {
"buildCommand": "npm run build",
"outputPath": "dist",
"cloudPath": "/watch-todolist"
}
}
}
}
}
yarn dev
git clone https://github.com/oteam-sources/watch-todolist.git
yarn deploy:database
yarn dev
npm run dev
yarn deploy
npm run deploy
预览部署后的示例
点击文末阅读原文进入云开发社区官网,了解云开发的更多信息。
点击在看让更多人发现精彩
微信扫一扫
关注该公众号