Vue.js (2) : Vue-resource Kullanarak Veri Çekmek

Vue.js ile ilgili yazı dizimize devam ediyoruz. Bu yazımızda vue-resource kütüphanesini kullanarak bir rest servisinden veri getireceğiz. Http get/post metodlarını kullanarak, rest kaynaklar üzerinde işlem yapacağız.

Vue-resource Nedir ?

vue-resource, vue topluluğu tarafından geliştirilmiş bir http client kütüphanesidir. Http web çağrılarını yapmak ve geriye dönen dönüş değerlerini okuyabilmek için gerekli servisleri sunan bir plugindir. Vue.js’nin kullanmış olduğumuz 2 nolu versiyon ile de uyumlu bir şekilde çalışmaktadır.

Rest api olarak https://jsonplaceholder.typicode.com/ servisini kullanacağız. jsonplaceholder, herkesin kullanabileceği, test amaçlı hazırlanmış bir servis. Bu servisin http get, post, put vs… metodlarını kullanarak uygulamamızı geliştireceğiz.

UserList Örneği

Çok zaman kaybetmeden, user verilerini çeken basit bir örnek yapalım:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>        
        <script src="https://unpkg.com/vue-resource@1.0.3/dist/vue-resource.min.js"></script>        
    </head>
    <body>
        <div id="app">
            <table border=1>
                <thead>
                    <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>username</th>
                        <th>email</th>
                    </tr>
                </thead>
                <tr v-for="user in userList">
                    <td>{{user.id}}</td>
                    <td>{{user.name}}</td>
                    <td>{{user.username}}</td>
                    <td>{{user.email}}</td>
                </tr>
            </table>           
        </div>
        <script>
            var app = new Vue({
                el: '#app',
                data: {
                    userList: []
                },
                mounted: function() {
                    var root = 'https://jsonplaceholder.typicode.com/users';
                    this.$http.get(root).then(function (resp) {
                        if (resp.status == 200) {
                            this.userList = resp.data;
                        }
                    }); 
                }            
            });      
        </script>
    </body>
</html>

Vue.js kütüphanesinde ingilizcesi life cycle hooks terimine karşılık gelen metodlar var. Bu metodlar model objesinin oluşturulması sırasında, belli bir sırayla çalıştırılır. created, mounted, destroyed, updated vs… Biz html sayfamız gösterilir gösterilmez veriyi çekmek istediğimiz için, mounted metodu ekliyoruz.

jsfiddle üzerinde de gösterelim:

Post Metodu

Örneğimizi biraz daha geliştirelim. Yeni bir user eklemek istiyoruz. Bir kaç text input alanı ve bir button ekleyelim.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>        
        <script src="https://unpkg.com/vue-resource@1.0.3/dist/vue-resource.min.js"></script>        
    </head>
    <body>
        <div id="app">
            <table>
                <tr><td>id</td><td><input type="text" v-model="newUser.id"/></td></tr>
                <tr><td>name</td><td><input type="text" v-model="newUser.name"/></td></tr>
                <tr><td>username</td><td><input type="text" v-model="newUser.username"/></td></tr>
                <tr><td>email</td><td><input type="text" v-model="newUser.email"/></td></tr>
                <tr><td></td><td><button v-on:click="addUser">Add New User</button></td></tr>                                               
            </table>             
            <table border=1>
                <thead>
                    <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>username</th>
                        <th>email</th>
                    </tr>
                </thead>
                <tr v-for="user in userList">
                    <td>{{user.id}}</td>
                    <td>{{user.name}}</td>
                    <td>{{user.username}}</td>
                    <td>{{user.email}}</td>
                </tr>
            </table>           
        </div>
        <script>
            var app = new Vue({
                el: '#app',
                data: {
                    userList: [],
                    newUser: {
                        id: '',
                        name: '',
                        username: '',
                        email: ''
                    }
                },
                mounted: function() {
                    var root = 'https://jsonplaceholder.typicode.com/users';
                    this.$http.get(root).then(function (resp) {
                        if (resp.status == 200) {
                            this.userList = resp.data;
                        }
                    }); 
                },
                methods: {
                    addUser: function() {
                        var posturl = 'https://jsonplaceholder.typicode.com/users';
                        this.$http.post(posturl,this.newUser).then(function (resp) {
                            if (resp.status == 201) {
                                console.log('basarili post');
                                this.userList.push(this.newUser);
                                this.newUser = {
                                    id: '',
                                    name: '',
                                    username: '',
                                    email: ''
                                };
                            }
                        });                        
                    }
                }                            
            });      
        </script>
    </body>
</html>

jsfiddle gösterimi:

v-model özelliğinin kullanımına dikkat edelim. v-model kullanarak, vue modelimizdeki newUser objesi ile html input alanlarımızı ilişkilendirmiş olduk.

Sonuç

vue-resource ile vue kütüphanesini birlikte kullanarak, interaktif, hızlı bir şekilde ajax uygulamaları geliştirebiliriz.

Spring Boot ve Vue.js

Bir arkadaşımızın talebi üzerine, daha önce geliştirmiş olduğumuz spring boot todo uygulamasını vue ve vue-resource kütüphanelerini kullanarak güncelleyelim.

TodoController classını aşağıdaki şekilde değiştirelim:

package com.onbirkod.controllers;

import com.onbirkod.models.Todo;
import com.onbirkod.models.TodoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class TodoController {
    @Autowired
    private TodoDao todoDao;

    @RequestMapping("/")
    public String index(Model model, @ModelAttribute Todo todo)
    {
        return "index";
    }
}

index.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Db app with Spring Boot</title>
    <script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-resource@1.0.3/dist/vue-resource.min.js"></script>
</head>
<body>
<h3>Todo Versiyon 1.0.2</h3>
<div>
    <p>
        Kayıt ekleyebilirsiniz
    </p>
</div>
<hr/>
<div style="font-size: medium; font-weight: bold;" id="app">
    <table>
        <tr><td>id</td><td><input type="text" v-model="newTodo.id"/></td></tr>
        <tr><td>description</td><td><input type="text" v-model="newTodo.description"/></td></tr>
        <tr><td></td><td><button v-on:click="addTodo">Add New Todo</button></td></tr>
    </table>
    <table border="1">
        <thead>
        <tr>
            <th>id</th>
            <th>description</th>
        </tr>
        </thead>
        <tr v-for="todo in todoList">
            <td>{{todo.id}}</td>
            <td>{{todo.description}}</td>
        </tr>
    </table>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            todoList: [],
            newTodo: {
                id: '',
                description: ''
            }
        },
        mounted: function() {
            var root = '/todolist';
            this.$http.get(root).then(function (resp) {
                if (resp.status == 200) {
                    this.todoList = resp.data;
                }
            });
        },
        methods: {
            addTodo: function() {
                var posturl = '/addtodo';
                this.$http.post(posturl,this.newTodo).then(function (resp) {
                    if (resp.status == 201) {
                        console.log('basarili post');
                        this.todoList.push(this.newTodo);
                        this.newTodo = {
                            id: '',
                            description: ''
                        };
                    }
                });
            }
        }
    });
</script>
</body>
</html>

Controller paketinin içerisine yeni bir sınıf ekleyelim (TodoRestController):

package com.onbirkod.controllers;

import java.util.Collection;
import java.util.List;

import com.onbirkod.models.Todo;
import com.onbirkod.models.TodoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * Created by ttufekci on 23.10.2016.
 */
@RestController
public class TodoRestController {
    @Autowired
    private TodoDao todoDao;

    @RequestMapping("/todolist")
    public Collection<Todo> todolist()
    {
        List<Todo> todos = (List<Todo>) todoDao.findAll();
        return todos;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> addtodo(@RequestBody Todo todo)
    {
        todoDao.save(todo);
        HttpHeaders httpHeaders = new HttpHeaders();
        return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
    }
}

Todo sınıfında da id alanını public yapalım:

package com.onbirkod.models;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "Todo")
public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    @NotNull
    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Bu şekilde çalıştıralım ve uygulamanın son halini görelim:

 

 

2 thoughts on “Vue.js (2) : Vue-resource Kullanarak Veri Çekmek”

Yorum bırakın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir