Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
在解決問題之道上不斷前行
GAS(google app script) 是 google 服務提供的腳本平台,最廣為熟知的就是可以透過 script 將 google sheet 擴充許多自動化功能,甚至可以部署網頁等。若有興趣可以查查看,可以多查查看,如果你有大量的 google 相依服務,就能考慮使用 GAS 提供工作效率。
這次的需求就是將 google sheet 當作是簡易資料表,然後輸出到 GAS 的網頁做檢視,考慮到未來可能的擴充性,決定導入 Vue3 的 CDN 版本來實作。
首先就是啟用 GAS ,這邊就不特別教學,請參考原本的教學。
首先新增一個網頁,我取名為 output.html 。
再來新增一個 code.gs 。*.gs 是 GAS中專用的 script 副檔名。
在 code.gs 中加上以下程式碼。
function doGet(){
let template = HtmlService.createTemplateFromFile('output');
let dataObj = {};
template.data = dataObj;
return template.evaluate().setTitle("Vuejs Demo");
}
HtmlService 是 GAS 中建立網頁的函式,這樣就能將資料輸出至 output.html ,並且設定標題 Vuejs Demo 。一定要取名為doGet
並且能把名為 dataObj 的物件丟到該文檔中。
output.html 這隻檔案則就加入一般的 html 文件,例如
...
...
接下來就是建立 Vue3 的環境。我們使用 CDN 引入,可以直接像這樣
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
接著要宣告 Vue 實體,為了方便管理我另外開了一隻檔案 app-js.html
裡面其實就是宣告建立 Vue
<script>
const { createApp, ref } = Vue
const app = createApp({
components: { },
data() {
return {
}
},
watch:{
},
methods: {
},
created: function(){
});
app.mount("#app");
</script>
然後記得 output.html 需要預留一個可以建立 Vue 的位置,並且還要引入剛剛那隻 app-js.html
<body>
<div class="" id="app">
....
<?!= include('app-js'); ?>
</body>
這樣就快完成了,只需要部署就可以使用囉~
如果需要取用 google sheet 內的資料,則需要在 code.gs 中另外使用函式與資料表溝通。以下為範例。
function doGet(){
let template = HtmlService.createTemplateFromFile('output');
let dataObj = {};
dataObj.Data = getDB(); // 這是取得資料的函式
template.data = dataObj;
return template.evaluate().setTitle("Vuejs and SpreadSheet Demo").setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getDB(){
const activeSheet = SpreadsheetApp.getActiveSheet();
let dataItems = activeSheet.getDataRange().getValues().slice(1);
return dataItems;
}
這是最簡單的寫法, SpreadsheetApp 就是使用 GAS 跟 google sheet 溝通,有興趣就詳見 GAS 的各種應用。
在 GAS 的管理介面中,右上角可以看到部署的按鈕。如果開發時可以使用「測試部署作業」,如果是正式使用則要「新增部署作業」,兩者差異在於「測試部署作業」會給予一個..../dev結尾的位置,並且每次修改儲存後會立即生效,「新增部署作業」的話會以該次程式碼版本部署,會給予一個..../exec的位置,但記得程式碼修改後不會立即生效,要使用每次部署後取得的位置才有用。