GASとVue.jsでWebアプリケーションを作る方法
GAS(Google Apps Script)と、Vue.jsを使って、簡単なWebアプリケーションを作成します。
以下の記事のVue.js使用版です。
nmmmk.hatenablog.com
GASをGoogle Driveに追加する
GASをGoogle Driveに追加済みの方は、読み飛ばしてください。
Google Driveを開いて、「新規」を押下します。
その他 -> アプリを追加を押下します。
Google Apps Scriptをインストールします。
その他 -> Google Apps Scriptを押下して、スクリプトを作成します。
GASプロジェクトを作成する
以下のようにGASプロジェクトを作成します。
HTML/CSS/JavaScriptファイルを作成する
ファイル -> 新規作成 -> HTMLファイルを選択します。
ファイル名を入力します。
以下の3つのファイルを準備します。
・index.html
・css.html
・js.html
簡単なアプリケーションを作ってみる
現在時刻を1秒ごとに更新するプログラムを作成します。
main.gs
doGet関数は、WebアプリケーションのURLが叩かれたときにコールされます。
function doGet() { var htmlOutput = HtmlService.createTemplateFromFile("index").evaluate(); htmlOutput .setTitle('Sample') .addMetaTag('viewport', 'width=device-width, initial-scale=1') return htmlOutput; }
var htmlOutput = HtmlService.createTemplateFromFile("index").evaluate();
の部分で、index.htmlを呼び出すようにしています。
index.html
<!DOCTYPE html> <html> <head> <base target="_top"> <?!= HtmlService.createHtmlOutputFromFile('css').getContent(); ?> </head> <body> <div id="app"> <p class="now-time-title">現在時刻</p> <div>{{ nowTime }}</div> </div> <?!= HtmlService.createHtmlOutputFromFile('js').getContent(); ?> </body> </html>
<?!= HtmlService.createHtmlOutputFromFile('js').getContent(); ?>
の部分でjs.htmlを呼び出しています。(css.htmlも同様。)
css.html
cssを適用して、「現在時刻」という文字列部分を青文字にします。
styleタグが必要であることに注意してください。
<style> .now-time-title { color: blue; } </style>
js.html
1秒ごとに現在時刻を更新する処理を作成します。
Vue.jsは、CDNから読み込みます。
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <script> new Vue({ el: '#app', data: { nowTimer: null, nowTime: '' }, methods: { updateTime: function() { this.nowTime = new Date().toLocaleString(); } }, mounted: function() { this.nowTimer = setInterval(this.updateTime, 1000); }, destroyed: function() { clearInterval(this.updateTime); } }); </script>
アプリケーションを公開する
公開 -> ウェブ アプリケーションとして導入 を選択します。
以下の内容で更新ボタンを押下します。
項目 | 内容 | 備考 |
---|---|---|
プロジェクトバージョン | 新規作成 | プログラムを更新する度に、新規作成にする必要がある |
アプリケーションにアクセスできるユーザー | 全員(匿名ユーザーを含む) | 公開範囲に合わせて変更してください |
動作確認する
ウェブ アプリケーションとして導入を行った際に、割り当てられる「現在のウェブ アプリケーションのURL」にアクセスします。
以下のような表示で、時刻が1秒更新されればOKです。