使用vue前端框架實現單頁應用(SPA)
阿新 • • 發佈:2019-01-07
- ArthurSlog
- SLog-6
Year·1
Guangzhou·China
- July 13th 2018
時間 時間 時間 每一份有限的時間裡 都飽含無限的價值 需要非常珍惜
開發環境MacOS(High Sierra 10.13.5)
需要的資訊:
brew官方手冊,一款MacOS工具,具體內容請移步官方手冊
npm官方手冊,一刻nodejs程式碼包管理工具,具體內容請移步官方手冊
chrome瀏覽器devtools擴充套件,用於除錯Vue.js應用程式,下一篇進行詳細介紹和應用,本篇先自己花一分鐘做個瞭解
vue快速使用手冊,可以先花20分鐘的時間寫一寫感受一下vue的寫法
執行方案
- 切換至桌面路徑
cd ~/Desktop
- 建立一個新資料夾
mkdir node_vue_learningload
- 切換至新建的資料夾路徑下
cd node_vue_learningload
- 使用npm指令初始化nodejs專案環境,一路回車,完成初始化
npm init
- 安裝 koa 和 kao-static
sudo npm install koa koa-static
需要管理員許可權,輸入密碼
在當前路徑下建立 index.js 和 index.html 這兩個檔案
index.js
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
// $ GET /package.json
app.use(serve('.'));
app.listen(3000);
console.log('listening on port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- 開發環境版本,包含了有幫助的命令列警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>ArthurSlog</title>
</head>
<body>
<div id="app">{{ message }}</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello ArthurSlog!'
}
})
</script>
</body>
</html>
分析一下上面的兩份檔案程式碼:
- 在 index.js 裡,引入 koa 框架和 koa-static 中介軟體實現了一個 靜態web伺服器,靜態路由至當前路徑下的 index.html
- 在 index.html 裡,引入 vue框架:
index.html
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
- 在 index.html 裡,vue.js 使用簡潔的模板語法來宣告式地將資料渲染進DOM的系統:
index.html
<body>
<div id="app">{{ message }}</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello ArthurSlog!'
}
})
</script>
</body>
index.html
<div id="app">{{ message }}</div>
index.js
new Vue({
el: '#app',
data: {
message: 'Hello ArthurSlog!'
}
})
Vue 在背後做了大量工作。現在資料和 DOM 已經被建立了關聯,所有東西都是響應式的
- 現在啟動由 koa框架 和 koa-static中介軟體 搭建的靜態web伺服器
node index.js
- 現在開啟瀏覽器,在位址列輸入靜態web伺服器的地址 127.0.0.1:3000 ,可以看到頁面顯示
Hello ArthurSlog!
至此,我們使用 vue框架 實現了一個單頁應用
下一節,會介紹 後端框架koa 搭配 前端框架vue,實現前後端的銜接