Welcome Guest, Not a member yet? Register   Sign In
[WIP] Codeigniter 4 and Vue SPA (Vue Cli)
#1

(This post was last modified: 06-12-2020, 05:52 AM by Paradinight.)

A little tutorial. Work in progress.

1. Installing CodeIgniter 4

composer create-project codeigniter4/appstarter example --no-dev

2. Installing Vue in the CodeIgniter directory
cd example
vue create frontend --no-git

3. Move all files from example/public to example/frontend/public

4. Create a vue.config.js in the frontend directory

Code:
// vue.config.js
module.exports = {
    // options ...
    devServer: {
        proxy: {
            '/api': {
                target: 'http://example.test/',
            }
        }
    },
    indexPath: process.env.NODE_ENV === 'production' ? '../app/Views/index.php' : 'index.html',
    outputDir: '../public/',
};

- target is the url from the test server
- indexPath and outputDir // after "npm run build" the build script move the example/frontend/public/index.html to example/app/Views/index.php and The example/frontend/public/ directory to the example/public directory.
Warning: The npm run build delete the example/public directory and recreate it.

5.
example Code.


PHP Code:
/**
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */


$routes->group('api', ['namespace' => 'App\Controllers\Api'], function($routes)
{
    $routes->get('test''Test::index');
});

// Catch-all Route...
$routes->get('''Home::index');
$routes->get('(:any)''Home::index'); 

example/app/Controllers/Api/Test.php
PHP Code:
<?php namespace App\Controllers\Api;

use 
CodeIgniter\API\ResponseTrait;

class 
Test extends \CodeIgniter\Controller
{
    use ResponseTrait;

    public function index() {
        return $this->respond([
            ['id' => 1'name' => 'abc'],
        ],200);
    }


Catch-all Controller.

PHP Code:
<?php namespace App\Controllers;

class 
Home extends BaseController
{
 public function 
index()
 {
 return 
view('index');
 }


example/frontend/src/views/Home.vue
Code:
<template>
  <div class="home">
    <ul>
      <li v-for="row in testdaten" :key="row.id">
        {{ row.name }}
      </li>
    </ul>
  </div>
</template>

<script>

import axios from 'axios';

export default {
  name: 'Home',
  data() {
    return {
      testdaten: []
    }
  },
  mounted() {
    axios.get('/api/test').then(response => {
      this.testdaten = response.data
    })
  }
}
</script>
Reply
#2

Nice, very helpful!
Reply
#3

How do you set it up if you want to use vue components in several different Controller/Views ?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB