chaihongjun.me

thinkphp5.0+Vue前后端分离demo

这个demo的由来,其实非常简单,企业在各个平台注册的账户都需要手机绑定,而这手机可能会因为人员流动问题而有变动,弄一个记录表登记持有人,方便其他人联系。

用到的技术项目,Vue+axios+tp5。

thinkphp5.0+Vue前后端分离demo

前端代码:

<!--  application/index/view/brand/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>品牌手机号</title>
    <link
      rel="stylesheet"
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css"
    />
    <style>
      [v-cloak] {
        display: none;
      }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <div class="container-fluid">
        <div class="row">
          <div class="col-lg-12 col-sm-12 col-md-12 col-xl-12">
            <h1 class="text-center">品牌手机号查询</h1>
          </div>
        </div>
        <div class="row">
          <div class="table-responsive col-lg-12 col-sm-12 col-md-12 col-xl-12">
            <table class="table table-striped text-nowrap table-bordered">
              <thead class="table-info">
                <tr>
                  <th>序号</th>
                  <th>品牌</th>
                  <th>手机号</th>
                  <th>持有人</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(result,index) of results" :key="index" v-cloak>
                  <td>
                    {{index+1}}
                  </td>
                  <td>
                    {{result.name}}
                  </td>
                  <td>
                    <input
                      type="text"
                      name="mobile"
                      v-model="result.mobile"
                      :disabled="index != isActive"
                    />
                  </td>
                  <td>
                    <input
                      type="text"
                      name="owner"
                      v-model="result.owner"
                      :disabled="index != isActive"
                    />
                  </td>
                  <td>
                    <div class="btn-group btn-group-sm" role="group">
                      <button
                        type="button"
                        class="btn btn-warning"
                        @click="change(index)"
                      >
                        修改
                      </button>
                      <button
                        type="button"
                        class="btn btn-primary"
                        @click="save(index)"
                      >
                        保存
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-12 col-sm-12 col-md-12 col-xl-12">
            <footer class="text-center">网络部版权所有</footer>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
<script>
  // 页面加载初始化数据
  window.addEventListener("load", function () {
    axios
      .get("http://192.168.0.122:8080/api/brand/index")
      .then(function (res) {
        // console.log(res.data);
        vm.results = res.data;
        // console.log(vm.results);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
  let vm = new Vue({
    el: "#app",
    data: {
      isActive: -1,
      results: [],
    },
    methods: {
      change(index) {
        // 点击索引 index
        this.isActive = index;
      },
      // 保存更新的数据
      save(index) {
        this.isActive = -1;
        let id = index + 1;
        let mobile = document.getElementsByName("mobile")[index].value;
        let owner = document.getElementsByName("owner")[index].value;
        console.log(mobile);
        console.log(owner);
        let formData = {
          id,
          mobile,
          owner,
        };
        // console.log(formData);
        axios({
          method: "post",
          url: "http://www.tp5.com:8080/api/brand/update",
          header: {
            "Content-Type": "application/json;charset=utf-8",
          },
          data: formData,
        })
          .then(function (res) {
            console.log("提交的数据成功:");
            console.log(res);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
    },
  });
</script>

接口路由配置:

// application/route.php
//显示页面
Route::get('index/brand/index', 'index/brand/index');
// 后台接口数据
Route::get('api/brand/index', 'api/brand/index');
// 提交服务器接口
Route::post('api/brand/update', 'api/brand/update');

第一个是路由配置是首页,第二个路由配置是用于异步获取后台数据的,第三个则是前端修改的数据更新到后台数据库。

关于控制器配置:

//application/index/controller/Brand.php
<?php
namespace app\index\controller;
use think\Controller;
class Brand extends Controller
{
  public function index()
  {
    return $this->fetch();
  }
}

以上用于访问显示页面。而接口控制器:

//application/api/controller/Brand.php
<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use  app\common\model\Brand as BrandModel;
class Brand extends Controller
{
  //显示
  public function index(Request $request)
  {
    //api/brand/index
    header('Access-Control-Allow-Origin:*');
    // 响应类型
    header('Access-Control-Allow-Methods:GET');
    $brands = collection(BrandModel::all())->toArray();
    return json($brands);
  }
  //保存
  public function update(Request $request)
  {
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Methods:POST');
    header('Content-Type:application/json;charset=utf-8');
    if ($request->isPost()) {
      $id =  $request->param('id');
      $mobile =  $request->param('mobile');
      $owner =  $request->param('owner');
      $data['mobile'] = $mobile;
      $data['owner'] = $owner;
      $result = BrandModel::where('id', $id)->update($data);
      if ($result) {
        $this->success('更新成功!');
      } else {
        $this->error('更新成功!');
      }
    }
  }
}

另外就是表结构:

thinkphp5.0+Vue前后端分离demo

  • 跨域配置(前端配置和后端配置,主要是后端起决定作用)

  • 数据格式的校验(前端校验或者后端校验)

  • 数据提交格式的选择(application/x-www-form-urlencoded和multipart/form-data )

  • 知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:柴宏俊»