Tutorial Laravel 12 – Membuat Web Berita berbasis API – Bagian #3 (Vue.js – Vue Router)

BAGIAN G — Vue Router (SPA Navigation)

Pada bagian ini kita akan memecah tampilan menjadi beberapa halaman menggunakan Vue Router, seperti aplikasi profesional.


17. Install Vue Router

Pastikan berada di folder vue-berita:

npm install vue-router

18. Konfigurasi Router

Buat file src/router/index.js:

import { createRouter, createWebHistory } from 'vue-router'
import ListBerita from '../pages/ListBerita.vue'
import FormBerita from '../pages/FormBerita.vue'

const routes = [
{ path: '/', component: ListBerita },
{ path: '/tambah', component: FormBerita }
]

const router = createRouter({
history: createWebHistory(),
routes
})

export default router

19. Daftarkan Router ke Aplikasi

Edit src/main.js:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App)
.use(router)
.mount('#app')

20. Struktur Folder Pages

src/
├─ pages/
│ ├─ ListBerita.vue
│ └─ FormBerita.vue

21. Halaman ListBerita.vue

<script setup>
import { ref, onMounted } from 'vue'
import api from '../plugins/axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const beritas = ref([])

const loadData = async () => {
const res = await api.get('/berita')
beritas.value = res.data
}

const hapus = async (id) => {
if (confirm('Yakin hapus?')) {
await api.delete(`/berita/${id}`)
loadData()
}
}

onMounted(loadData)
</script>

<template>
<h2>Daftar Berita</h2>
<button @click="router.push('/tambah')">Tambah Berita</button>

<ul>
<li v-for="b in beritas" :key="b.id">
<b>{{ b.judul }}</b>
<br />
{{ b.isi }}
<br />
<button @click="hapus(b.id)">Hapus</button>
</li>
</ul>
</template>

22. Halaman FormBerita.vue

<script setup>
import { ref } from 'vue'
import api from '../plugins/axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const judul = ref('')
const isi = ref('')

const simpan = async () => {
await api.post('/berita', {
judul: judul.value,
isi: isi.value
})

router.push('/')
}
</script>

<template>
<h2>Tambah Berita</h2>

<input v-model="judul" placeholder="Judul" />
<textarea v-model="isi" placeholder="Isi"></textarea>
<br />
<button @click="simpan">Simpan</button>
</template>

23. Update App.vue

<template>
<router-view />
</template>

BAGIAN H — Testing SPA

24. Skenario Uji Router

  • Halaman / → list berita tampil ✔
  • Klik tambah → pindah ke /tambah
  • Simpan → kembali ke list ✔
Tags :

Leave a Reply

Your email address will not be published. Required fields are marked *

18 − one =

Tutorial Terpopuler

Tutorial Pilihan

Tentang Gurututorku

Gurututorku adalah sebuah kursus online maupun offline yang menyediakan berbagai macam tutorial tentang pemrograman, design, dan multimedia serta artikel teknologi yang tentunya bisa dinikmati dan dipelajari oleh semua orang yang baru ingin belajar dunia IT.

© 2024 – Gurututorku.com | Learning today success tomorrow.