Vue.js先后端通用组件开发心得-菜鸟篇

项目状况

我使用的是express作为服务器框架,只须要调用后台API接口得到数据,而后把数据渲染成html就能够了。最好能使用一套模板渲染先后端的数据,也就是模板和某些简单组件能够同构。
服务端渲染vue组件,使用vue-server这个插件。他的用法和vue差很少。这样作的目的是首屏服务端渲染,提高页面展现速度。html

开发组件

由于须要让服务端也能使用,单.vue文件的开发方式我目前是没有找到可让node读取的方式,因此就暂时放弃了。
还有下面这种写死组件名字的方式也不太合适前端

Vue.component('my-component', { /* ... */ })  //这样写须要引入Vue,可是先后端的Vue不是一个东西

因此我选择了只输出一个个简单组件对象的方式,以下 modal.jsvue

clipboard.png

为何template模板要直接写在里面呢?

答:由于会有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

相关文章
相关标签/搜索