本文記錄了學習 vue.js 過程中,透過 webpack 打包並製作評論列表與分頁兩個小組件的實踐,重點在於父子組件間的通訊與數據綁定。
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
<style type="text/css">
* { margin: 0; padding: 0; font-family: 'Open Sans', Arial, sans-serif; }
.contianer { width: 50%; height: auto; margin: 20px auto; }
article { margin-bottom: 50px; }
</style>
</head>
<body>
<div class='contianer'>
<article>
文章內容...
</article>
<div id='main'>
<app></app>
</div>
</div>
<script type="text/javascript" src='bundle.js'></script>
</body>
</html>
將 app 組件放在 <div id='main'></div> 內,透過 webpack 打包後,入口 js 文件是 entry.js,用來引入 app.vue 組件。
let Vue = require('vue');
import App from './components/app';
let app_vue = new Vue({
el: '#main',
components: { app: App }
});
<style type="text/css" scoped>
</style>
<template>
<comment :cur-page-index="curPageIndex" :each-page-size="eachPageSize" :comment-url="commentUrl" :comment-params="commentParams" :comment-is-sync="commentIsSync">
</comment>
<page :cur-page-index.sync="curPageIndex" :each-page-size="eachPageSize" :page-url="pageUrl" :page-params="pageParams" :page-is-sync="pageIsSync">
</page>
</template>
<script type="text/javascript">
import Comment from './comment';
import Page from './page';
export default {
data () {
return {
curPageIndex: 1,
eachPageSize: 7,
}
},
components: {
comment: Comment,
page: Page
},
}
</script>
它有 comment.vue 和 page.vue 兩個子組件,透過動態綁定數據進行父子通訊。對於「當前在第幾頁」應當由 page.vue 傳遞給 app.vue,所以這裡使用雙向綁定;其餘如 params、url、isSync 則是向後台請求數據及是否同步/異步操作的配置。
<style type="text/css" scoped>
.comt-mask { opacity: 0.5; }
.comt-line { width: 100%; height: 2px; background-color: #CCC; margin: 10px 0; }
.comt-user { float: left; }
.comt-img { width: 34px; height: 34px; border-radius: 17px; }
.comt-context { margin: 0 0 0 60px; }
.comt-name { color: #2B879E; margin-bottom: 10px; font-size: 18px; }
</style>
<template>
<div v-if="hasComment" :class="{'comt-mask': loading}">
<h3 class='comt-title'>{{ totalCommentCount }} 條評論</h3>
<div class="comt-line"></div>
<div class="comt-wrap" v-for="comment of commentArr">
<div class="comt-user">
<img src='{{ comment.avatar }}' class="comt-img"/>
</div>
<div class="comt-context">
<p class="comt-name">{{ comment.name }}</p>
<p> {{ comment.context }} </p>
</div>
<div class="comt-line"></div>
</div>
</div>
</template>
<script type="text/javascript">
import {getCommentData, getTotalCommentCount} from './getData';
export default {
props: {
curPageIndex: { type: Number, default: 1, },
eachPageSize: { type: Number, default: 7, },
commentUrl: { type: String, default: '', },
commentParams: { type: Object, default: null, },
commentIsSync: { type: Boolean, default: true, },
},
data () {
return {
totalCommentCount: 0,
hasComment: false,
loading: true,
}
},
computed: {
commentArr () {
this.loading = true;
let res = getCommentData(this.commentUrl, this.commentParams, this.commentIsSync, this.curPageIndex, this.eachPageSize);
this.loading = false;
return res;
},
},
created () {
let cnt = getTotalCommentCount(this.commentUrl, this.commentParams);
this.totalCommentCount = cnt;
this.hasComment = cnt > 0;
}
}
</script>
hasComment 在組件首次加載時請求總數據長度,若無數據則不顯示布局內容;curPageIndex 透過父組件傳遞,使用 props 接收,並為每個 prop 設置默認值與類型。
<style type="text/css" scoped>
.page { text-align: center; margin: 30px; }
.page-btn { color: gray; background-color: white; border: white; width: 30px; height: 30px; margin: 5px; font-size: 18px; outline: none; }
.page-btn-link { cursor: Crosshair; }
.page-btn-active { border: 1px solid gray; border-radius: 15px; }
</style>
<template>
<div class="page">
<button v-for="pageIndex of pageArr" track-by='$index' :class="{'page-btn': true, 'page-btn-active': this.curPageIndex === pageIndex, 'page-btn-link': checkNum(pageIndex)}" @click="clickPage(pageIndex)" >
{{ pageIndex }}
</button>
</div>
</template>
<script type="text/javascript">
import {getTotalPageCount} from './getData';
export default {
props: {
totalPageCount: { type: Number, default: 0, },
curPageIndex: { type: Number, default: 1, },
eachPageSize: { type: Number, default: 7, },
pageAjcn: { type: Number, default: 4, },
pageUrl: { type: String, default: '', },
pageParams: { type: Object, default: null, },
pageIsSync: { type: Boolean, default: true, }
},
data () { return { } },
computed: {
pageArr () {
let st = 1, end = this.totalPageCount, cur = this.curPageIndex, ajcn = this.pageAjcn, arr = [], left = Math.floor(ajcn / 2), right = ajcn - left;
if (end == 0 || cur == 0) { return arr; }
else {
arr.push(st);
if (st + 1 < cur - left) { arr.push('...'); }
for (let i = Math.max(cur - left, st + 1); i <= cur - 1; ++i) { arr.push(i); }
if (cur != st) { arr.push(cur); }
for (let i = cur + 1; i <= cur + right && i <= end - 1 ; ++i) { arr.push(i); }
if (cur + right < end - 1) { arr.push('...'); }
if (end != cur) { arr.push(end); }
return arr;
}
}
},
methods: {
clickPage (curIndex) {
if (Number.isInteger(curIndex)) { this.curPageIndex = curIndex; }
},
checkNum (curIndex) { return Number.isInteger(curIndex); }
},
created () {
this.totalPageCount = getTotalPageCount(this.pageUrl, this.pageParams, this.pageIsSync, this.eachPageSiz);
}
}
</script>
這裡主要運用組件事件(最常見的 click)、class 與 style 綁定,透過 computed 計算屬性獲得頁碼數組,並在 created 時計算總頁碼。
let dataArr = [];
function randomStr (len) {
return Math.random().toString(36).substr(len);
}
function initData () {
for (var i = 0; i<45 ; ++i) {
let _avator = "./resources/" + i%7 + ".jpg";
let _name = randomStr(20);
let _context = randomStr(2);
dataArr.push({ avatar: _avator, name: _name, context: _context });
}
}
if (!dataArr.length) { initData(); }
export function getCommentData (url = '', params = null, isSync = true, curPageIndex = 1, eachPageSize = 7) {
/* ajax */
let st = (curPageIndex - 1) * eachPageSize;
let end = st + eachPageSize;
return dataArr.slice(st, end);
}
export function getTotalCommentCount(url = '', params = null, isSync = true) {
/* ajax */
return dataArr.length;
}
export function getTotalPageCount(url = '', params = null, isSync = true, eachPageSize = 7) {
/* ajax */
return Math.floor((dataArr.length + eachPageSize -1 ) / eachPageSize);
}
這就用 vue.js 完成了評論與分頁兩個組件,數據獲取部分目前以靜態數據模擬,後續可替換為真實的 ajax 請求。