vue实现个推
使用 Vue 实现个推(消息推送)功能
1. 安装个推 SDK
在 Vue 项目中安装个推的 Web SDK 或对应的客户端 SDK(如使用 Cordova/ Capacitor 等混合开发框架)。通过 npm 或 yarn 安装:
npm install getui --save
2. 初始化个推 SDK
在 Vue 的入口文件(如 main.js)或组件中初始化个推。需要传入个推提供的 AppID 等配置信息:
import { GeTui } from 'getui';
const geTui = new GeTui({
appId: 'YOUR_APP_ID',
appKey: 'YOUR_APP_KEY',
appSecret: 'YOUR_APP_SECRET'
});
3. 绑定设备并获取 CID
个推需要通过 CID(Client ID)标识设备。在 Vue 组件中调用绑定接口:
mounted() {
geTui.bindAlias(this.userId).then(() => {
console.log('绑定成功');
});
geTui.getClientId().then(cid => {
this.cid = cid;
});
}
4. 监听推送消息
设置消息监听器,接收服务器推送的消息:
created() {
geTui.onMessage(message => {
console.log('收到推送消息:', message);
this.showNotification(message);
});
},
methods: {
showNotification(message) {
if (Notification.permission === 'granted') {
new Notification('新消息', { body: message.payload });
}
}
}
5. 处理点击通知行为
配置通知点击后的跳转逻辑:
geTui.onNotificationClicked(payload => {
this.$router.push({ path: '/message-detail', query: { id: payload.messageId } });
});
服务端配置示例
Node.js 服务端推送代码

const GeTui = require('getui-server');
const gt = new GeTui({
appId: 'YOUR_APP_ID',
appKey: 'YOUR_APP_KEY',
masterSecret: 'YOUR_MASTER_SECRET'
});
async function pushToClient(cid, title, content) {
await gt.pushMessage({
cid: cid,
title: title,
body: content,
payload: { key: 'value' }
});
}
注意事项
- 在浏览器环境下需要用户授权通知权限
- 个推的 Web SDK 依赖 Service Worker,需在
public目录放置个推的 worker 文件 - 生产环境需要配置 HTTPS,因为推送 API 和 Service Worker 要求安全上下文
- 不同平台(iOS/Android/Web)的个推配置参数可能不同






