商品エンティティクラス(Item.java)
public class Item {
private String code;
private String title;
private double cost;
private int quantity;
// アクセサメソッド
}
商品管理サービス(ItemManager.java)
public class ItemManager {
private List<Item> inventory = new ArrayList<>();
public List<Item> fetchAllItems() {
return inventory;
}
public void registerItem(Item item) {
inventory.add(item);
}
public void deleteItem(String code) {
inventory.removeIf(i -> i.getCode().equals(code));
}
}
RESTコントローラ(ItemController.java)
@RestController
@RequestMapping("/api/items")
public class ItemController {
@Autowired
private ItemManager itemManager;
@GetMapping
public List<Item> fetchAllItems() {
return itemManager.fetchAllItems();
}
@PostMapping
public void registerItem(@RequestBody Item item) {
itemManager.registerItem(item);
}
@DeleteMapping("/{code}")
public void deleteItem(@PathVariable String code) {
itemManager.deleteItem(code);
}
}
Spring Boot起動クラス(Bootstrap.java)
@SpringBootApplication
public class Bootstrap {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
}
商品カタログコンポーネント(ItemCatalog.vue)
<template>
<div>
<h2>商品一覧</h2>
<ul>
<li v-for="item in inventory" :key="item.code">
{{ item.title }} - {{ item.cost }}円
<button @click="deleteItem(item.code)">削除</button>
</li>
</ul>
<h2>商品登録</h2>
<form @submit.prevent="registerItem">
<input type="text" v-model="title" placeholder="商品名" required>
<input type="number" v-model="cost" placeholder="価格" required>
<button type="submit">登録</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
inventory: [],
title: '',
cost: 0
};
},
async created() {
await this.loadInventory();
},
methods: {
async loadInventory() {
const response = await fetch('/api/items');
this.inventory = await response.json();
},
async registerItem() {
const newItem = { title: this.title, cost: this.cost, quantity: 0 };
await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newItem)
});
this.title = '';
this.cost = 0;
this.loadInventory();
},
async deleteItem(code) {
await fetch(`/api/items/${code}`, { method: 'DELETE' });
this.loadInventory();
}
}
};
</script>
プロキシ設定(vue.config.js)
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
};