Vue.js(Vue-CLI 3) +cakephp +mysql SPA開発(11) #Vue.js #web #php
index:
準備など
・cakephp2, ver2 を clone
https://github.com/cakephp/cakephp
・事前にDBの、作成。
表(tasks) の作成。
https://github.com/kuc-arc-f/apiphp1_ver1/blob/master/db/tasks.sql
・Linux の場合、mod_rewrite エラーが出る場合
a2enmod で有効化
sudo a2enmod rewrite
・rewrite の確認
ls -l /etc/apache2/mods-enabled/ | grep rewrite
・AllowOverride の設定
/etc/apache2/sites-available/000-default.conf
<Directory "/var/www/html/apiphp1"> AllowOverride All </Directory>
・ apacheの再起動
sudo systemctl restart apache2
・cakeの書込みエラーが出る場合は、権限の追加。
chmod -R 777 app/tmp/
実装など
コントローラ TasksController.php
https://github.com/kuc-arc-f/apiphp1_ver1/blob/master/app/Controller/TasksController.php
api_index
// public function api_index() { $this->Task->recursive = 0; $this->Paginator->settings = array( 'limit' => 10 ,'order'=> array('Task.id'=>'desc') ); $dats = $this->Paginator->paginate(); $arr = array(); foreach ($dats as $dat){ $arr[] = $dat["Task"]; } header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); echo(json_encode($arr )); exit(); }
api_add
public function api_add() { if ($this->request->is('post')) { $this->Task->create(); $json =''; if ($this->Task->save($this->request->data)) { $json = json_encode(['title' => $this->request->data["Task"] ]); } else { $json = json_encode(['message' => 'The task could not be saved. Please, try again.' ]); } header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); echo( $json ); exit(); } }
Vue.js 側
Index.vue
https://github.com/kuc-arc-f/vue_2_cake/blob/master/src/components/Tasks/Index.vue
import axios from 'axios' import {Mixin} from '../../mixin' export default { mixins:[Mixin], created () { this.baseUrl = this.sysConst.API_BASE; console.log( this.baseUrl ) this.getTasks() }, data () { return { tasks: [], user_id : '', baseUrl : '' } }, methods: { getTasks() { var url = this.baseUrl +'tasks/api_index' console.log(url) axios.get(url) .then(res => { this.tasks = res.data console.log(res.data.length ) }) }, } }