在Vue 3开发前端应用时,你可以使用多种浏览器原生API。这些API是现代浏览器内置的功能,无需额外安装依赖。以下是一些常用的原生API分类及示例:
1. 网络请求
- Fetch API:现代的AJAX替代方案,用于发送HTTP请求。
1
2
3
4fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.data = data)
.catch(error => console.error('Error:', error)); - WebSocket:用于建立持久的双向通信连接。
1
2const socket = new WebSocket('ws://echo.websocket.org');
socket.onmessage = (event) => this.message = event.data;
2. 浏览器存储
- localStorage:永久存储数据(除非手动清除)。
1
2
3
4// 存储数据
localStorage.setItem('user', JSON.stringify(this.user));
// 获取数据
const user = JSON.parse(localStorage.getItem('user')); - sessionStorage:会话期间存储数据(窗口关闭后清除)。
1
sessionStorage.setItem('token', '12345');
3. 地理定位
- Geolocation API:获取用户地理位置。
1
2
3
4navigator.geolocation.getCurrentPosition(
position => this.location = position.coords,
error => console.error('Error:', error)
);
4. 设备API
- Camera/Microphone:访问设备摄像头和麦克风。
1
2
3navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => this.videoStream = stream)
.catch(error => console.error('Error:', error)); - Battery Status API:获取设备电池状态。
1
2
3navigator.getBattery().then(battery => {
this.batteryLevel = battery.level;
});
5. Web Storage与IndexedDB
- IndexedDB:用于存储大量结构化数据。
1
2const request = indexedDB.open('myDatabase', 1);
request.onsuccess = (event) => this.db = event.target.result;
6. Web Workers
- 用于在后台线程执行复杂计算,避免阻塞UI。
1
2
3const worker = new Worker(new URL('./worker.js', import.meta.url));
worker.postMessage('Start calculation');
worker.onmessage = (event) => this.result = event.data;
7. Notification API
- 显示系统通知。
1
2
3
4
5Notification.requestPermission().then(permission => {
if (permission === 'granted') {
new Notification('New Message', { body: 'You have a new message!' });
}
});
8. 拖拽API
- 实现拖放功能。
1
2<div draggable="true" @dragstart="onDragStart">Drag me</div>
<div @dragover="onDragOver" @drop="onDrop">Drop here</div>
9. Canvas API
- 用于图形绘制。
1
2
3const ctx = this.$refs.canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
10. Web Crypto API
- 用于加密和解密数据。
1
2crypto.subtle.digest('SHA-256', new TextEncoder().encode('data'))
.then(hash => this.hash = hash);
11. Web Animations API
- 实现高性能动画。
1
2
3
4this.$refs.element.animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 1000, easing: 'ease-out' }
);
12. Service Workers
- 用于离线支持和后台同步。
1
2
3if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
13. History API
- 操作浏览器历史记录。
1
2
3
4
5
6// 添加新历史记录
history.pushState({ page: 1 }, 'Title', '?page=1');
// 监听历史变化
window.addEventListener('popstate', (event) => {
this.page = event.state?.page || 1;
});
14. Window对象
- 访问浏览器窗口属性和方法。
1
window.addEventListener('resize', () => this.width = window.innerWidth);
15. Web Share API
- 调用系统分享功能。
1
2
3
4
5
6
7if (navigator.canShare) {
navigator.share({
title: 'My App',
text: 'Check out this app!',
url: window.location.href
});
}
注意事项:
- 兼容性:使用前需检查浏览器兼容性(可参考caniuse.com)。
- 异步处理:多数API是异步的,需使用
async/await
或.then()
处理。 - 安全限制:部分API(如摄像头、地理位置)需要用户授权。
- Vue 3集成:在Vue组件中使用时,建议在
onMounted
生命周期钩子中初始化API。
这些原生API可以显著增强Vue 3应用的功能和用户体验,同时避免引入额外的依赖。