Vue如何读取MySQL数据库数据

概述

Vue是一种用于构建用户界面的渐进式JavaScript框架。它可以与后端数据库进行交互,读取和显示数据。在本篇文章中,我们将探讨如何使用Vue读取MySQL数据库数据,并展示了一个完整的示例。

前提条件

在开始之前,确保您已经安装了Vue.js和MySQL,并且具有必要的数据库连接凭据。

步骤

步骤1:创建Vue应用

首先,我们需要创建一个新的Vue应用程序。您可以使用Vue CLI或在HTML页面中引入Vue.js脚本来创建Vue应用程序。以下是一个使用Vue CLI创建Vue应用程序的示例:

```bash
npm install -g @vue/cli
vue create my-app
cd my-app
npm run serve

### 步骤2:配置MySQL数据库连接
接下来,我们需要配置Vue应用程序以连接到MySQL数据库。我们将使用`mysql` npm包来实现这一点。

首先,安装`mysql` npm包:

```markdown
```bash
npm install mysql

然后,创建一个名为`db.js`的新文件,并将以下代码复制到其中:

```markdown
```javascript
const mysql = require("mysql");

// 创建数据库连接池
const pool = mysql.createPool({
  host: "localhost",
  user: "your_username",
  password: "your_password",
  database: "your_database_name",
});

// 导出数据库连接池
module.exports = pool;

请确保将`your_username`,`your_password`和`your_database_name`替换为您的实际数据库凭据。

### 步骤3:创建Vue组件
现在,我们将创建一个Vue组件来读取和显示MySQL数据库中的数据。创建一个名为`Users.vue`的新文件,并将以下代码复制到其中:

```markdown
```html
<template>
  <div>
    用户列表
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>邮箱</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.email }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
    };
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      // 导入数据库连接池
      const pool = require("./db");

      // 查询数据库中的用户数据
      pool.query("SELECT * FROM users", (error, results) => {
        if (error) {
          console.error(error);
        } else {
          this.users = results;
        }
      });
    },
  },
};
</script>

<style>
table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}
</style>

在上面的代码中,我们首先定义了一个表格,用于显示用户数据。然后,在组件的data函数中,我们定义了一个users数组,用于存储从数据库中读取的用户数据。

created生命周期钩子函数中,我们调用fetchUsers方法来从数据库中获取用户数据。

fetchUsers方法使用之前创建的数据库连接池,并执行一个查询语句来获取所有用户数据。查询结果将存储在results变量中,并将其赋值给users数组。

最后,我们使用v-for指令在表格中循环渲染用户数据。

步骤4:使用Vue组件

最后一步是在Vue应用程序中使用我们刚刚创建的组件。打开App.vue文件,并用以下代码替换其中的内容:

```html
<template>
  <div id="app">
    <Users />
  </div>
</template>

<script>
import Users from "./Users.vue";

export default {
  name: "App",
  components: {
    Users,
  },
};
</script>

<style>
#app {
  font-family: "Avenir", sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}