Home  >  Article  >  Backend Development  >  How to use PHP and Vue to implement data synchronization function

How to use PHP and Vue to implement data synchronization function

WBOY
WBOYOriginal
2023-09-25 16:05:14608browse

How to use PHP and Vue to implement data synchronization function

How to use PHP and Vue to implement data synchronization function

Foreword:
In modern web application development, data synchronization is a very important function. Data synchronization means that when the data on the back-end server changes, the front-end page can obtain the latest data in a timely manner and update the page accordingly. This article will introduce how to use PHP and Vue to implement data synchronization function, and provide specific code examples.

1. Acquisition and update of back-end data
In the back-end, we can use PHP to operate the database and obtain and update data. Suppose we have a student performance management system that contains students' names and performance information. Below is a simple PHP file used to obtain student performance data.

<?php
// 获取数据库连接
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 查询学生成绩数据
$sql = "SELECT * FROM students";
$result = $conn->query($sql);

// 将查询结果转换为关联数组
$data = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// 将数据转换为JSON格式并输出
echo json_encode($data);

$conn->close();
?>

In the above code, we first established a connection with the database and queried the student's performance data. Then, the query results are converted into an associative array, and the data is converted into JSON format for output. In this way, the front-end page can obtain the latest student performance data by sending an Ajax request.

2. Implementation of the front-end page
In the front-end, we can use Vue.js to bind and update data. Suppose we have a student performance management system page that uses Vue.js as the front-end framework. Below is a simple Vue component used to display student performance data.

<template>
  <div>
    <table>
      <tr>
        <th>姓名</th>
        <th>成绩</th>
      </tr>
      <tr v-for="student in students" :key="student.id">
        <td>{{ student.name }}</td>
        <td>{{ student.grade }}</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      students: []
    };
  },
  mounted() {
    this.fetchStudents();
  },
  methods: {
    fetchStudents() {
      // 发送Ajax请求获取学生成绩数据
      // 这里假设后端数据接口为 /api/getStudents.php
      fetch('/api/getStudents.php')
        .then(response => response.json())
        .then(data => {
          this.students = data;
        });
    }
  }
};
</script>

In the above code, we define a Vue component to display student performance data. A students array is defined in the data of the component to store the obtained student performance data. The fetchStudents method is called in the mounted hook of the component, which sends an Ajax request to obtain the latest student performance data. Then, assign the obtained data to the students array to update the data on the page.

3. Implement the data synchronization function
The key to realizing the data synchronization function is to promptly notify the front-end page to update when the back-end data changes. This can be achieved through WebSocket technology. This article does not introduce the principles of WebSocket in detail, but only provides a simple sample code.

The following is a simple PHP file used to broadcast to the front-end page through WebSocket after receiving new student performance data.

<?php
// 获取WebSocket连接
$server = new SwooleWebSocketServer('0.0.0.0', 9501);

// 监听WebSocket连接事件
$server->on('open', function ($server, $request) {
    echo "新的连接建立:" . $request->fd . "
";
});

// 监听WebSocket消息事件
$server->on('message', function ($server, $frame) {
    echo "收到消息:" . $frame->data . "
";
});

// 监听WebSocket关闭事件
$server->on('close', function ($server, $fd) {
    echo "连接关闭:" . $fd . "
";
});

// 启动WebSocket服务
$server->start();
?>

In the above code, we first created a WebSocket server and listened to the open, message and close events. When a new connection is established, the connection ID will be output; when a message is received, the content of the message will be output; when the connection is closed, the closed connection ID will be output.

In the front-end page, we can use WebSocket technology to communicate with the back-end and update the data on the page when new student performance data is received. The following is a simple Vue component example that shows how to use WebSocket to implement data synchronization function.

<template>
  <div>
    <table>
      <tr>
        <th>姓名</th>
        <th>成绩</th>
      </tr>
      <tr v-for="student in students" :key="student.id">
        <td>{{ student.name }}</td>
        <td>{{ student.grade }}</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      students: []
    };
  },
  mounted() {
    this.fetchStudents();

    // 建立WebSocket连接
    this.socket = new WebSocket('ws://localhost:9501');

    // 监听WebSocket消息事件
    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.action === 'addStudent' || data.action === 'updateStudent') {
        // 新增或更新学生数据
        this.students.push(data.student);
      } else if (data.action === 'deleteStudent') {
        // 删除学生数据
        this.students = this.students.filter(student => student.id !== data.student.id);
      }
    };
  },
  methods: {
    fetchStudents() {
      // 发送Ajax请求获取学生成绩数据
      // 这里假设后端数据接口为 /api/getStudents.php
      fetch('/api/getStudents.php')
        .then(response => response.json())
        .then(data => {
          this.students = data;
        });
    }
  },
  beforeDestroy() {
    // 关闭WebSocket连接
    this.socket.close();
  }
};
</script>

In the above code, we established the WebSocket connection in the mounted hook and processed the message sent by the backend in the onmessage event. When new student performance data is received, it is determined whether to add, update or delete student data by judging the action attribute in the message. According to different operations, update the students array on the page to synchronize the data.

Summary:
Using PHP and Vue to implement the data synchronization function requires the coordination of back-end data acquisition and update, front-end page data binding and update, and data synchronization function. Obtain the latest data by sending Ajax requests, and use WebSocket to monitor changes in back-end data and update the data on the front-end page in a timely manner. This article provides specific code examples to help readers better understand and implement the data synchronization function. I hope this article will be helpful to everyone in practice.

The above is the detailed content of How to use PHP and Vue to implement data synchronization function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn