博客案例

更新时间: 2025-11-19 11:19:55

# 创建新项目引入uni-id-pages用户体系

  • 新建一个项目,选择空白模板,vue3,uniCloud选择支付宝云,然后关联一下服务空间
  • 下载uni-id-pages并导入
  • 在uniCloud/cloudfunctions/common/uni-config-center/目录下新建/uni-id/config.json
{
  "passwordSecret": [
    {
      "type": "hmac-sha256",
      "version": 1
    }
  ],
  "passwordStrength": "medium",
  "tokenSecret": "daodao123",
  "requestAuthSecret": "daodao123",
  "tokenExpiresIn": 7200,
  "tokenExpiresThreshold": 3600, 
  "maxTokenLength": 10, 
  "passwordErrorLimit": 6,
  "passwordErrorRetryTime": 3600,
  "autoSetInviteCode": false, 
  "forceInviteCode": false,
  "idCardCertifyLimit": 1, 
  "realNameCertifyLimit": 5, 
  "sensitiveInfoEncryptSecret": "",
  "frvNeedAlivePhoto": false, 
  "userRegisterDefaultRole": ["user"], //给用户设置默认权限 
  "app": { 
    "tokenExpiresIn": 2592000,
    "tokenExpiresThreshold": 864000,
    "oauth": {
      "weixin": {
        "appid": "",
        "appsecret": ""
      },
      "qq": {
        "appid": "",
        "appsecret": ""
      },
      "apple": {
        "bundleId": ""
      },
      "huawei": {
        "clientId": "",
        "clientSecret": ""
      }
    }
  },
  "web": {
    "tokenExpiresIn": 7200,
    "tokenExpiresThreshold": 3600,
    "oauth": {
      "weixin-h5": {
        "appid": "",
        "appsecret": ""
      },
      "weixin-web": {
        "appid": "",
        "appsecret": ""
      }
    }
  },
  "mp-weixin": {
    "tokenExpiresIn": 259200,
    "tokenExpiresThreshold": 86400,
    "oauth": {
      "weixin": {
        "appid": "",
        "appsecret": ""
      }
    }
  },
  "mp-qq": {
    "tokenExpiresIn": 259200,
    "tokenExpiresThreshold": 86400,
    "oauth": {
      "qq": {
        "appid": "",
        "appsecret": ""
      }
    }
  },
  "mp-alipay": {
    "tokenExpiresIn": 259200,
    "tokenExpiresThreshold": 86400,
    "oauth": {
      "alipay": {
        "appid": "",
        "privateKey": "", 
        "keyType": "PKCS8" 
      }
    }
  },
  "mp-harmony": {
      "oauth": {
        "huawei": { 
          "clientId": "",
          "clientSecret": ""
        }
      }
  },
  "service": {
    "sms": {
      "name": "",
      "codeExpiresIn": 180, 
      "scene": {
        "bind-mobile-by-sms": { 
          "templateId": "", 
          "codeExpiresIn": 240 
        }
      }
    },
    "univerify": {
      "appid": "" 
    }
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

然后就可以上传database,启动项目试试能不能注册登录

# beforeRegister注册前钩子设置默认昵称

uni-id钩子函数需要在uni-config-center内配置。在uni-config-center/uni-id下创建hooks目录并在其内创建index.js内容如下

function beforeRegister({
  userRecord,
  clientInfo
} = {}) {
	if(!userRecord.nickname) {
	  userRecord.nickname = "匿名"+Math.random().toString(36).substring(3,9)
	} 
	return userRecord // 务必返回处理后的userRecord
}

module.exports = {
  beforeRegister
}
1
2
3
4
5
6
7
8
9
10
11
12
13

我们再注册一个账号试试

可以看到昵称已经设置好了

# 布局梳理博客新增喝列表页面并到如扩展组件

创建两个页面,页面很基础就不赘述了,直接看截图的效果

# 创建blog的schema表结构创建云对象新增方法


参考这张表,我们创建pro-blog.schema.json,然后上传DB schema

{
	"bsonType": "object",
	"required": [
		
	],
	"permission": {
		"read": true,
		"create": "auth.uid != null",
		"update": "doc.user_id == auth.uid",
		"delete": "doc.user_id == auth.uid"
	},
	"properties": {
		"_id": {
			"description": "存储文档 ID(用户 ID),系统自动生成"
		},
		"user_id": {
			"bsonType": "string",
			"description": "作者ID, 参考`uni-id-users` 表",
			"foreignKey": "uni-id-users._id",
			"defaultValue": {
				"$env": "uid"
			}
		},
		"content": {
			"bsonType": "string",
			"description": "内容"
		},
		"pics" :{
			"bsonType": "array",
			"description": "图片组",
			"defaultValue": []
		},
		"publish_date": {
			"bsonType": "timestamp",
			"title": "发表时间",
			"description": "发表时间",
			"defaultValue": {
				"$env": "now"
			}
		},
		"publish_ip": {
			"bsonType": "string",
			"title": "发布文章时IP地址",
			"description": "发表时 IP 地址",
			"forceDefaultValue": {
				"$env": "clientIP"
			}
		}
	},
	"version": "0.0.1"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

然后创建云对象

const dbJQL = uniCloud.databaseForJQL()

module.exports = {
	_before: function () { // 通用预处理器

	},
	async add(params = {}) {
		return await dbJQL.collection("pro-blog").add(params)
	}
}
1
2
3
4
5
6
7
8
9
10

页面中调用云对象

const blogCloudObj = uniCloud.importObject("blogCloudObj")

const onSubmit = async () => {
	console.log(formData.value)
	let params = {
	    ...formData.value,
	    pics: formData.value.pics.map(item => ({
	      name: item.name, 
	      extname: item.extname, 
	      url: item.url
	    }))
	  }
	let {errCode} = await blogCloudObj.add(params)
	if(errCode == 0) {
		uni.showToast({
			title:"发布成功",
			icon: "none"
		})
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 云对象使用JQL需要配置getClientInfo()获取客户端信息

但是我们发现现在是无法新增成功的,因为之前是在客户端调用,可以知道用户信息,但是在云对象里,不知道用户信息,所以不行

我们可以在云对象中用 this.getClientInfo()获取客户端信息

module.exports = {
	_before: function () { // 通用预处理器

	},
	async add(params = {}) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo:this.getClientInfo()
		})
		return await dbJQL.collection("pro-blog").add(params)
	}
}
1
2
3
4
5
6
7
8
9
10
11

在路由页面配置uniIdRouter

//....
"uniIdRouter": {
		// #ifdef MP-WEIXIN 
		"loginPage":"uni_modules/uni-id-pages/pages/login/login-withoutpwd",
		// #endif 
		// #ifndef MP-WEIXIN 
		"loginPage":"uni_modules/uni-id-pages/pages/login/login-withpwd",
		// #endif 
		"needLogin": [
			"pages/blog/edit"
		]
		
	} 
1
2
3
4
5
6
7
8
9
10
11
12
13

我们发一条试试,发布成功了

可以看到数据库理也新增成功了

# JQL联表查询将博客数据展示到列表页面

先写一下云对象中的list方法,传入page和pageSize代表当前页码和每页的数量

async list({page=1,pageSize=10} = params) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const skipSize = (page - 1) * pageSize
		const blogTemp = dbJQL.collection("pro-blog").getTemp()
		const userTemp = dbJQL.collection("uni-id-users").field("_id, nickname").getTemp()
		return await dbJQL.collection(blogTemp, userTemp).orderBy("publish_date desc").skip(skipSize).limit(pageSize).get({getCount:true})
	}
1
2
3
4
5
6
7
8
9

然后对接一下list页面

import { ref } from 'vue'

const blogCloudObj = uniCloud.importObject("blogCloudObj")
const blogList = ref([])

const page = ref(1)
const pageSize = ref(10)

const getData = async () => {
	let {errCode, data} = await blogCloudObj.list({
		page:page.value,
		pageSize:pageSize.value
	})
	blogList.value = [...blogList.value, ...data]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# getCurrentUserInfo获取当前用户信息控制操作权限

  • 手动指定管理员
    给admin这个用户添加一个role字段,这样设置代表最高权限,写别的都不行

新建common.js

export function isPermission(userid) {
	const {uid="", role=[]} = uniCloud.getCurrentUserInfo()  
	
	if(uid == userid || role.includes("admin")) {
		return true
	}else{
		return false
	}
}
1
2
3
4
5
6
7
8
9

在需要判断是否是自己发布内容的地方调用这个方法就可以了

# 删除用户发布的博客记录

云对象中编写remove方法

	async remove(id) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		return await dbJQL.collection("pro-blog").doc(id).remove()
	}
1
2
3
4
5
6

页面中调用

// 删除一条博客  
const remove = async (id) => {
	let feedback = await uni.showModal({
		title: "是否确认删除?"
	})
	if(!feedback.confirm) {
		return 
	}
	let {errCode} = await blogCloudObj.remove(id)
	if(errCode == 0) {
		blogList.value = []
		getData()
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 发布成功后更新列表页码uni.$emit全局自定义事件

uni.$emit(eventName, OBJECT)
触发全局自定义事件,附加参数都会传给监听器回调函数

uni.$on(eventName, callback)
监听全局的自定义事件,事件由uni.$emit触发,回调函数回接受事件触发函数的传入参数

# 打包H5上传部署云函数数据库自动上传到web托管

  • 先上传所有的云函数/云对象

  • 上传所有database

  • 切到连接云端函数

在H5上测试一下,看看有没有什么问题,没什么问题就可以打包了

# 打包H5

  • 配置一下web配置

  • 发行 》 网站PC或手机H5

然后提示部署完成,我们看一下控制台,已经部署好了

使用默认域名访问,也可以了

# 打包微信小程序

  • 配置一下微信小程序

  • 在uniCloud/common/uni-config-center/uni-id/config.json中配置微信小程序一键登录,将appid和appsecret 配置好

  • 重新上传uni-config-center

先在本地启动一下小程序试一下

  • 在小程序控制台里将安全域名配置上

调试的时候可以将不校验合法域名勾上