前回 紹介したAPI-firstなフレームワークSynth とVue.js を組み合わせて使ってみる.
Synthの$ synth new my_app
で生成されるコードはAngular.js を使うようになっている.
Angular.js派ではないのでVue.js版に書き換えてみる.
ついでにcoffee-script 派なので,coffee-scriptで動くようにする.
ここまでのコードは前回 参照.Synth公式のチュートリアル を済ませた時点のコードです.
モジュールの準備
Vue.jsインストール
まず,Vue.jsを使うため,インストールする.
1
2
$ synth install -f vue
$ synth install -f jquery
Angularのアンインストール
Angularは使わないので抜く.$ synth uninstall -f angular
とやりたいが,未実装っぽい.
あと$ synth install -f
時に.bower.json
にmain
キーがないとfront/js/jsFiles
に記載されないっぽい
1
2
3
$ cd front
$ bower uninstall angular
$ bower uninstall angular-route
front/bower.json
からも消しておく.
1
2
3
4
5
6
7
8
9
$ cat front/bower.json
{
"name": "my_app",
"private": true,
"dependencies": {
"vue": "~0.10.5",
"jquery": "~2.1.1"
}
}
front/js/jsFiles
から不要になったファイルを削除する
1
2
3
4
$ cat front/js/jsFiles
../bower_components/jquery/dist/jquery.js
../bower_components/vue/dist/vue.js
front-app.js
テンプレートの修正
DirectivesをAngular用からVue用に書き換える.
dateのmedium
はVueでは無いので後でformatDate
を定義することにする.
1
2
3
4
5
6
7
$ cat front/html/tweets/getIndex.jade
textarea(v-text="newTweet")
button(v-on="click: publish()", v-attr="disabled: newTweet.length == 0") Publish
ul.tweet-timeline
li.tweet(v-repeat="tweet : tweets")
.content
.date
front/index.jade
もVue用に色々修正
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
doctype html
html
head
meta(charset='utf-8')
meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
meta(name='viewport', content='width=device-width, initial-scale=1.0')
title= appName
for cssFile in cssFiles
link(rel="stylesheet", href=cssFile)
// Preloaded Data
script.
window.preloadedData = !{data};
for jsFile in jsFiles
script(src=jsFile)
body
h1= appName
div#content
if preloadHTML
script.template(type="v-template", id="template")
!= preloadHTML
分からなかった点
1
script(type="text/ng-template", id="#{preloadHTMLPath}")
とかなっててngRouteのtemplateUrl
らへんでバインドしてた方法のVue版が分からなかったから普通にid指定にしてしまった.
Vueのバインディングとcoffee-script化
front/front-app.js
を消してfront/front-app.coffee
にしてVue版にする
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ ->
Vue.filter "formatDate", (v) ->
v.replace /T|Z/g, " "
content = new Vue
el: "#content"
template: "#template"
data:
newTweet: "write some tweet."
created: ->
if typeof window.preloadedData isnt "undefined"
@$data = window.preloadedData
window.preloadedData = null
else
$.ajax
url: "/api/tweets"
success: (data) =>
@$data.tweets = data?.tweets
methods:
publish: ->
$.ajax
type: "POST"
url: "/api/tweets"
data:
content: @$data.newTweet
dataType: "json"
success: (tweet) =>
@$data.tweets.unshift tweet
@$data.newTweet = ""
合わせてfront/js/jsFiles
も書き換え
1
2
3
4
$ cat front/js/jsFiles
../bower_components/jquery/dist/jquery.js
../bower_components/vue/dist/vue.js
front-app.coffee
これでめでたくTweetが表示されて,投稿できるようになった.
まとめ
synthのAngularで動いてたのをVue版に書き直してみた
そんなに変更は難しくなかった.これから新しいクライアントサイドのライブラリが出てきてもサッと変えてテスト出来そう.
よく考えたら当たり前だけどbackend側全然いじってない
API増やしたり,色々するとまたbackend側のディレクトリ構成とかfrontのhtml以下のディレクトリ構成とかハマるポイントが有るけどそれは次の話にする.