LoginSignup
2
6

More than 1 year has passed since last update.

VueでのAPI

Last updated at Posted at 2019-09-13

時代はSPA

SinglePageApplication
紙芝居をイメージ。
JavaScript上でページの中身を変えるので
URLもvue-routerなどを使えば変えられるので
そう。サーバーと通信して新たなhtmlやJSPのページを必要としない
1枚のページをころころ変えていくアプリケーション

軽い。便利。

ページ遷移の方法

vue-routerを使います

router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home/'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: qwq
    }
  ]
})

componentがページの内容で、これが何枚もある感じ。
1枚ごとにURLを設定して、まるで今までのサーバー通信のアプリケーションのようにふるまえる

APIの呼び方

main.js
//  Ajax通信ライブラリ
import axion from './axios'
qwq.js
<script>
import ...
export default{
    data: function () {
        return {
            id: '',
            name: [],
            obj: null
        },
    methods: {
        suica: function () {
            console.log('スイカだよ')
        },
        melon: function () {
            console.log('メロンだよ')
        }
        mounted: function () {
            //  リクエストを生成
            const params = {
                'wawa' : this.id,
                'sasa' : this.name
            }
            //  APIたたく
            this.$api
                .post('http://google', JSON.stringfy(params), {
                    headers: {
                        'Content-Type' : 'application/json'
                    }
                })
                .then (response => {
                    this.obj = response.data.responseBody
                }).catch(error => {
                    console.errer(errer)
                }).then(() => {
                })
        }
    }
}
</script>

みたいなね
mounted()ってfunctionはページ読み込み後、最初に行われるやつ!
今回はそこでapi読んでます
だいたい英語の通りなので詳細な説明は割愛しますが、SpringでAPI呼び出すときと同じ感じですよね

#API側(Spring)

サーバー側でのControllerメソッドを、APIとして扱います。
ようはjavascript側からControllerを呼ぶってことです。

サーバーとの通信がページ遷移のためでなく、何か他のロジックを使うためって感じですね。

ServerController.java
@RestController
@RequestMapping("/hello")
public class ServerController {

    //こういうserviceがあったとする
    @Autowired
    private ServerService service;

    @RequestMapping("/hi")
    public WebApiResponse<Dto> wawa(@RequestBody Wawa wawa) {
        WebApiResponse<Dto> response = new WebApiResponse<Dto>();
        //serviceでなにか処理をする
        Dto dto = service.sasa(wawa);
        response.setResponseBody(dto);
        return response;
    }
}

言わずもがなな感じですよね
WebApiResponseを使ってやり取りします
Modelもいい感じに自由に設定できるので楽ですね

で?

例のごとく書きなぐりです。
次第にアップデートしていければ嬉しいです!!

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6