我使用的是express作爲服務器框架,只須要調用後臺API接口得到數據,而後把數據渲染成html就能夠了。最好能使用一套模板渲染先後端的數據,也就是模板和某些簡單組件能夠同構。
服務端渲染vue組件,使用vue-server這個插件。他的用法和vue差很少。這樣作的目的是首屏服務端渲染,提高頁面展現速度。html
由於須要讓服務端也能使用,單.vue文件的開發方式我目前是沒有找到可讓node讀取的方式,因此就暫時放棄了。
還有下面這種寫死組件名字的方式也不太合適前端
Vue.component('my-component', { /* ... */ }) //這樣寫須要引入Vue,可是先後端的Vue不是一個東西
因此我選擇了只輸出一個個簡單組件對象的方式,以下 modal.jsvue
答:由於會有2種引入方式,前端是能夠預編譯好的沒有問題,可是後端調用 import 'XXX.html' 這句話就可能執行不了。node
#index.js 輸出組件的文件 import modal from './component/modal/modal' exports.modal = modal
import Vue from 'vue' import { picker, modal, toast, alert, preloader, indicator, actions, pullToRefresh, infiniteScroll } from '../src/index' //使用前端的Vue定義組件和指令的名稱 Vue.component('picker',picker); Vue.component('modal',modal); Vue.component('toast',toast); Vue.component('alert',alert); Vue.component('preloader',preloader); Vue.component('indicator',indicator); Vue.component('actions',actions) Vue.directive('pull-to-refresh',pullToRefresh) Vue.directive('infinite-scroll',infiniteScroll)
這樣前端就能夠正常使用這個組件了git
import { picker, modal, toast, alert, preloader, indicator, actions, pullToRefresh, infiniteScroll } from '../src/index' let vueServer = require('vue-server') //服務端Vue let Vue = new vueServer.renderer(); //頁面模板 let tpl = fs.readFileSync(config.PATH_WEBAPP + '/states/index/template.html', 'utf-8'); //vue實例 vm = new Vue({ replace: false, template: tpl, components : { picker : picker, modal : modal, toast : toast, alert : alert }, data: { } }); //渲染好html的事件 vm.$on('vueServer.htmlReady', function (html) { res.render('layout', {server_html:html}); //這個html就是vue服務端渲染好的,而後能夠經過ejs或者其餘模板引擎輸出到layout中。 });
ok 這種通用組件寫法只適合比較簡單的項目。比較適合寫一次綁定生成頁面元素的組件,好比列表,佈局這種組件。github