code igniter integration - sikaeducation/vue-curriculum GitHub Wiki

Integrating Vue.js with Code Igniter 3

Steps

Make a components folder in /application/views. This is where you'll put all of your components, one per file. Make sure you're wrapping the component in <script></script> tags. This will declare a global JS variable containing your component data:

// /application/views/components/app-counter.php

<script>
  const AppCounter = {
    props: {
      greeting: String,
    },
    data() {
      return {
        counter: 0
      }
    },
    mounted() {
      setInterval(() => {
        this.counter++
      }, 1000)
    },
    template: `
      <div class="app-counter">
        <h2>{{greeting}}</h2>
        <p>Counter: {{counter}}</p>
      </div>
    `
  }
</script>

Then, in the view that your controller will render, include:

  • A container to mount the Vue app in
  • The CDN script to include Vue
  • A script with your top-level component, incorporating any data that will be passed from the controller
  • A script that creates the app, registers any neccessary components, and mounts the app in the container
// /application/views/some-view.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><body>
  <div id="app"></div>

  <script src="https://unpkg.com/vue@3"></script>
  <script>
    const App = {
      name: "App",
      data() {
        return {
          heading: "<?php echo $heading; ?>",
          greetings: [
            <?php foreach ($greetings as $greeting): ?>
              "<?php echo $greeting; ?>",
            <?php endforeach; ?>
          ],
        }
      },
      template: `
        <h1>{{heading}}</h1>
        <ul>
          <li v-for="greeting in greetings" :key="greeting">
            <app-counter :greeting="greeting" />
          </li>
        </ul>
      `
    }

    const app = Vue.createApp(App)
    app.component('app-counter', AppCounter)
    app.mount('#app')
  </script>
</body>

Then, in the controller for the view, load the any needed components before rendering the view:

// /application/controllers/SomeController.php

// ...
public function index()
{
  $data['heading'] = "This is integrated with Vue.js!";
  $data['greetings'] = array(
    'english' => 'Hello!',
    'spanish' => '¡Hola!',
    'german' => 'Guten tag!',
  );

  $this->load->view('header');
  $this->load->view('components/app-counter');
  $this->load->view('some-view', $data);
  $this->load->view('footer');
}
// ...
⚠️ **GitHub.com Fallback** ⚠️