MySQL数据库结合node.js和vue怎么使用
时间: 2023-05-14 17:06:10 浏览: 76
你可以使用 Node.js 的 MySQL 模块来连接 MySQL 数据库,并使用 Vue.js 来构建前端界面。以下是一个简单的示例代码:
```
// 引入 MySQL 模块
const mysql = require('mysql');
// 创建连接池
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
// 查询数据
pool.query('SELECT * FROM mytable', (error, results, fields) => {
if (error) throw error;
console.log(results);
});
// 插入数据
pool.query('INSERT INTO mytable (name, age) VALUES (?, ?)', ['John', 25], (error, results, fields) => {
if (error) throw error;
console.log(results);
});
```
在前端界面中,你可以使用 Vue.js 的组件来显示数据,并使用 axios 或者其他 HTTP 库来与后端进行通信。以下是一个简单的示例代码:
```
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }} - {{ item.age }}</li>
</ul>
<form @submit.prevent="submitForm">
<input v-model="name" type="text" placeholder="Name">
<input v-model="age" type="number" placeholder="Age">
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: [],
name: '',
age: ''
};
},
mounted() {
axios.get('/api/mytable').then(response => {
this.items = response.data;
});
},
methods: {
submitForm() {
axios.post('/api/mytable', { name: this.name, age: this.age }).then(response => {
this.items.push(response.data);
this.name = '';
this.age = '';
});
}
}
};
</script>
```
当然,这只是一个简单的示例,实际上你需要更多的代码来处理错误、验证输入等。希望这可以帮助你入门。