vue实现sql操作
Vue 中实现 SQL 操作的方法
Vue 本身是一个前端框架,不直接支持 SQL 操作。但可以通过以下方式间接实现与数据库的交互:
通过后端 API 连接数据库
前端 Vue 通过 HTTP 请求与后端通信,后端处理 SQL 操作并返回结果。
// Vue 组件中调用 API
methods: {
fetchData() {
axios.get('/api/data')
.then(response => {
this.data = response.data
})
}
}
使用浏览器端数据库
对于纯前端解决方案,可以使用浏览器端数据库:
IndexedDB 浏览器内置的 NoSQL 数据库,适合存储大量结构化数据。
// 打开数据库
const request = indexedDB.open('myDatabase', 1)
request.onsuccess = (event) => {
const db = event.target.result
const transaction = db.transaction('storeName', 'readwrite')
const store = transaction.objectStore('storeName')
// 添加数据
store.add({id: 1, name: 'test'})
}
WebSQL 已废弃但部分浏览器仍支持的关系型数据库。

// 执行 SQL 查询
const db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024)
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS test (id unique, name)')
tx.executeSql('INSERT INTO test (id, name) VALUES (1, "test")')
})
使用第三方库
sql.js 将 SQLite 编译为 JavaScript 的库,可在浏览器中运行完整 SQLite。
import initSqlJs from 'sql.js'
async function init() {
const SQL = await initSqlJs()
const db = new SQL.Database()
// 执行 SQL
db.run('CREATE TABLE test (id INT, name TEXT)')
db.run('INSERT INTO test VALUES (1, "test")')
const res = db.exec('SELECT * FROM test')
console.log(res)
}
本地开发解决方案
对于开发环境,可以使用 json-server 模拟 REST API:
-
安装 json-server

npm install -g json-server -
创建 db.json 文件
{ "posts": [ { "id": 1, "title": "test" } ] } -
启动服务器
json-server --watch db.json -
Vue 中调用
axios.get('http://localhost:3000/posts') .then(response => { console.log(response.data) })
安全注意事项
前端不应直接包含数据库凭据。所有涉及敏感信息的 SQL 操作都应通过后端 API 完成,前端只负责展示数据和触发操作请求。






